2015-12-07 6 views
2

Привет StackOverflow сообщества,Android ListView - Пользовательский адаптер не отображает ничего

я застрял с проблемой (глупый, наверное), где я не мог понять, что случилось с моим ListView. У меня есть пользовательский адаптер, и я могу передавать ему данные, но он ничего не отображает. Вот мой код:

LayoutInflater mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View view = mInflater.inflate(R.layout.nutrition_main, null); 
     listview = (ListView) view.findViewById(R.id.listView); 
     // Pass the results into an ArrayAdapter 
     ArrayAdapter adapter = new ArrayAdapter<>(getActivity(), 
       R.layout.listviewtextview); 

     for (ParseObject calories : ob) { 
      Log.i("Calories", calories.get("Calories").toString()); 
      adapter.add(calories.get("Calories") + ""); 
     } 

     ArrayList<String> kapow = new ArrayList<String>(); 
     for(int i = 0; i < adapter.getCount(); i++){ 
      String str = (String)adapter.getItem(i); 
      kapow.add(str); 
      Log.i("str", str); 
     } 
     SomeAdapter eh = new SomeAdapter(getActivity(), kapow); 
     listview.setAdapter(eh); 
     eh.notifyDataSetChanged(); 

Вот мой класс SomeAdapter код:

public class SomeAdapter extends ArrayAdapter<String> { 

private Context mContext; 
private ArrayList<String> mItem; 

public SomeAdapter(Context context, ArrayList<String> itemsArrayList) { 
    super(context, R.layout.listviewtextview, itemsArrayList); 
    this.mContext = context; 
    this.mItem = itemsArrayList; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View v = inflater.inflate(R.layout.listviewtextview, parent, false); 
    TextView mFoodName = (TextView) v.findViewById(R.id.food_name);v.findViewById(R.id.food_description); 
    mFoodName.setText(mItem.get(position) + ""); 
    return v; 
} 
} 

И последнее, но не менее, вот мой listviewtextview.xml файл:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:background="@drawable/row_activated" 
android:layout_height="88dp"> 

<LinearLayout 
    android:layout_height="88dp" 
    android:layout_width="match_parent" 
    android:layout_marginLeft="16dp" 
    android:gravity="center_vertical" 
    android:orientation="vertical"> 

    <TextView 
     android:id="@+id/food_name" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:maxLines="1" 
     android:textColor="@color/text_color" 
     android:textSize="16sp"/> 

    <TextView 
     android:id="@+id/food_brand" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/food_name" 
     android:singleLine="true" 
     android:textColor="@color/text_color" 
     android:textSize="14sp"/> 

    <TextView 
     android:id="@+id/food_description" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:paddingRight="16dp" 
     android:layout_below="@+id/label" 
     android:singleLine="true" 
     android:textColor="@color/text_color" 
     android:textSize="12sp"/> 
</LinearLayout> 

+0

Почему вы используете 'listview.setAdapter (а)' и ' eh.notifyDataSetChanged();' вместе? – Jas

+0

Является ли ваш макет правильно завышенным в своей деятельности? –

+0

Получение 'Log.i (" str ", str);' строка выполнена? –

ответ

0

у вас, похоже, есть неправильное представление о пользовательских списках и их адаптерах. Поскольку вы настраиваете свой список, s как eh вам даже не нужен этот адаптер массива, вы не только создали адаптер массива, но и ввели данные в него, а затем вы получили данные из адаптера массива один за другим и поместили его в kapow? Все, что вам нужно сделать, это инициализировать адаптер eh с данными и listview.setadapter(eh)

View view = mInflater.inflate(R.layout.nutrition_main, null); 
    listview = (ListView) view.findViewById(R.id.listView); 

    // YOU DONT NEED THIS ADAPTER ! 
    // Pass the results into an ArrayAdapter 
    // ArrayAdapter adapter = new ArrayAdapter<>(getActivity(), 
    //  R.layout.listviewtextview); 

    // just pass your calories string to the kapow list.     
    ArrayList<String> kapow = new ArrayList<String>(); 
    for (ParseObject calories : ob) { 
     Log.i("Calories", calories.get("Calories").toString()); 
     kapow.add(calories.get("Calories") + ""); 
    } 

    // You dont need this either 
    /*for(int i = 0; i < adapter.getCount(); i++){ 
     String str = (String)adapter.getItem(i); 
     kapow.add(str); 
     Log.i("str", str); 
    }*/ 

    SomeAdapter eh = new SomeAdapter(getActivity(), kapow); 
    listview.setAdapter(eh); 
    eh.notifyDataSetChanged(); 

EDIT

Ваш адаптер с viewholder

public class SomeAdapter extends ArrayAdapter<String> { 

    private Context mContext; 
    private ArrayList<String> mItem; 

    public SomeAdapter(Context context, ArrayList<String> itemsArrayList) { 
     super(context, R.layout.listviewtextview, itemsArrayList); 
     this.mContext = context; 
     this.mItem = itemsArrayList; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     ViewHolder viewHolder; 
     if(convertView == null) { 
      LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      convertView = inflater.inflate(R.layout.listviewtextview, parent, false); 
      ViewHolder viewHolder = new ViewHolder(); 
      viewHolder.textView = (TextView) v.findViewById(R.id.food_name);v.findViewById(R.id.food_description); 
      convertView.setTag(viewHolder); 
     } else { 
      viewHolder = (ViewHolder) convert.getTag(); 
     } 
     viewHolder.textView.setText(mItem.get(position) + ""); 
     return convertView; 
    } 

    private static class ViewHolder { 
     TextView textView; 
    } 
} 
+0

По какой-то причине я все еще ничего не получаю в ListView. Вы видите что-то еще не так? – Rohodude

+0

скажите, где вы указали вышеприведенный код в своей деятельности? также следуйте шаблону пользователя в вашем адаптере. – Bhargav

+0

Я поставил вышеуказанный код вместо того, где был мой предыдущий код (я прокомментировал предыдущий код). – Rohodude

0
public class AFrag extends Fragment{ 
    private View view = null; 
    public static final String TAG = "A"; 
    ListView listview; 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     if (view == null) { 
      view = inflater.inflate(R.layout.afrag, container, false); 
      listview = (ListView) view.findViewById(R.id.listView); 
      //Create your arraylist here no need to get it from adapter 
      // For testing & sample here i took characters loop. 
      ArrayList<String> kapow = new ArrayList<String>(); 
      for (char y = 'a'; y <= 'z'; y++) { 
       kapow.add(String.valueOf(y)); 
      } 
//   for (ParseObject calories : ob) { 
//    Log.i("Calories", calories.get("Calories").toString()); 
//    ///Fill arraylist direct from the parseobject. 
//    //no need to add to adapter & from adapter to arraylist 
//    kapow.add(calories.get("Calories") + ""); 
//   } 

      SomeAdapter eh = new SomeAdapter(getActivity(), kapow); 
      listview.setAdapter(eh); 
//   no need to call notifyDataSetChanged if you your data not changed after setting adapter 
//   eh.notifyDataSetChanged(); 
     } 
     return view; 
    } 

    public class SomeAdapter extends ArrayAdapter<String> { 

     private Context mContext; 
     private ArrayList<String> mItem; 

     public SomeAdapter(Context context, ArrayList<String> itemsArrayList) { 
      super(context, R.layout.listviewtextview, itemsArrayList); 
      this.mContext = context; 
      this.mItem = itemsArrayList; 
     } 

     public class ViewHolder { 
      public TextView txtFoodName; 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      ViewHolder v = null; 
      if (convertView == null) { 
       convertView = LayoutInflater.from(mContext).inflate(R.layout.listviewtextview, parent, false); 
       v = new ViewHolder(); 
       v.txtFoodName = (TextView) convertView.findViewById(R.id.food_name); 
       convertView.setTag(v); 
      } else { 
       v = (ViewHolder) convertView.getTag(); 
      } 
      v.txtFoodName.setText(mItem.get(position) + ""); 
      return convertView; 
     } 
    } 
} 

раскладка ListView Item

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 

    android:layout_height="88dp"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="88dp" 
     android:layout_marginLeft="16dp" 
     android:gravity="center_vertical" 
     android:orientation="vertical"> 

     <TextView 
      android:id="@+id/food_name" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:maxLines="1" 
      android:textColor="#FF0000" 
      android:textSize="16sp" /> 

     <TextView 
      android:id="@+id/food_brand" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_below="@+id/food_name" 
      android:singleLine="true" 
      android:textColor="#FF0000" 
      android:textSize="14sp" /> 

     <TextView 
      android:id="@+id/food_description" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_below="@+id/label" 
      android:paddingRight="16dp" 
      android:singleLine="true" 
      android:textColor="#FF0000" 
      android:textSize="12sp" /> 
    </LinearLayout> 
</RelativeLayout> 

Фрагмент основной макет

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <TextView android:id="@+id/txtCurrent" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="A" /> 

    <Button 
     android:id="@+id/btnClick" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:onClick="onBtnClick" 
     android:text="Go to B" /> 
    <ListView android:id="@+id/listView" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"></ListView> 
</LinearLayout> 

Если вы используете фрагмент, чем выше я писал код, а также дал комментарий по той же

предложение, пожалуйста, проверьте ViewHolder шаблон для ListView

И вы также можете проверить ниже ответы для связанных списков https://stackoverflow.com/a/28105884/1140237

https://stackoverflow.com/a/28104066/1140237

+0

Извините, но это тоже не получилось. Вы видите что-то еще не так? И да, я использую фрагмент. – Rohodude

+0

не могли бы вы разместить весь свой код? так как это должно работать. Может быть, что-то не так с другими вещами ... просто подтверждение декларации активности в манифесте, и замена фрагментов происходит правильно или нет ... – user1140237

Смежные вопросы