2015-12-12 2 views
0

Для начала я пытаюсь заполнить FrgamentList случайными данными, но список всегда пуст. Также попытался переключиться на фрагмент с ListView, но это тоже не сработало. Вот мой код проекта:Пустой список фрагментов с пользовательским адаптером

activity_main.xml:

<?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" > 

    <fragment 
     android:id="@+id/fragment1" 
     android:name="as400samplecode.com.myapplication.MyListFragment" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

</LinearLayout> 

fragment_item.xml:

<?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="horizontal" > 

    <ImageView 
     android:id="@+id/placeImage" 
     android:layout_width="60dp" 
     android:layout_height="60dp" 
     android:padding="5dp" /> 

    <LinearLayout android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:orientation="vertical"> 

     <TextView 
      android:id="@+id/placeName" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Medium Text" 
      android:textAppearance="?android:attr/textAppearanceMedium" 
      android:layout_marginLeft="10dp" 
      android:layout_marginTop="5dp" 
      android:padding="2dp" /> 
    </LinearLayout> 
</LinearLayout> 

list_fragment.xml:

<?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" > 

    <ListView 
     android:id="@android:id/list" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 
    </ListView> 

    <TextView 
     android:id="@android:id/empty" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 
    </TextView> 

</LinearLayout> 

Расположение:

public class Location { 
    public String locName; 
    public int locImage; 

    public Location(String locName, int locImage) { 
     this.locName = locName; 
     this.locImage = locImage; 
    } 
} 

MainActivity:

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 
} 

MyListFragment:

public class MyListFragment extends ListFragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.list_fragment, container, false); 

     return view; 
    } 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 

     super.onActivityCreated(savedInstanceState); 

     List<Location> locations = new ArrayList<>(); 
     locations.add(new Location("bla5", R.drawable.eiffel)); 
     locations.add(new Location("bla6", R.drawable.eiffel)); 

     CustomListAdapter adapter = new CustomListAdapter(getActivity(), locations); 

     setListAdapter(adapter); 
    } 
} 

CustomListAdapter:

public class CustomListAdapter extends ArrayAdapter<String> { 

    private final Activity context; 
    private List<Location> locations; 

    public CustomListAdapter(Activity context, List<Location> locations) { 
     super(context, R.layout.fragment_item); 
     this.context = context; 
     this.locations = locations; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     View v = convertView; 
     ViewHolder holder; // to reference the child views for later actions 

     if (v == null) { 
      LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      v = vi.inflate(R.layout.fragment_item, null); 
      // cache view fields into the holder 
      holder = new ViewHolder(); 
      holder.imageView = (ImageView) v.findViewById(R.id.placeImage); 
      holder.txtTitle = (TextView) v.findViewById(R.id.placeName); 

      holder.txtTitle.setText(locations.get(position).locName); 
      //holder.imageView.setImageBitmap(locations.get(position).locImage); 
      holder.imageView.setImageResource(locations.get(position).locImage); 

      // associate the holder with the view for later lookup 
      v.setTag(holder); 
     } 

     return v; 
    } 

    static class ViewHolder { 
     TextView txtTitle; 
     ImageView imageView; 
    } 
} 

Любая идея, что это может быть?

Спасибо!

ответ

0

проблема в этом методе

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    View v = convertView; 
    ViewHolder holder; // to reference the child views for later actions 

    if (v == null) { 
     LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     v = vi.inflate(R.layout.fragment_item, null); 
     // cache view fields into the holder 
     holder = new ViewHolder(); 
     holder.imageView = (ImageView) v.findViewById(R.id.placeImage); 
     holder.txtTitle = (TextView) v.findViewById(R.id.placeName); 

     holder.txtTitle.setText(locations.get(position).locName); 
     //holder.imageView.setImageBitmap(locations.get(position).locImage); 
     holder.imageView.setImageResource(locations.get(position).locImage); 

     // associate the holder with the view for later lookup 
     v.setTag(holder); 
    } 
    // although you have added a ViewHolder it is not used once your view is generated 
// you are just instantiating convertView if it is null and not doing anything after that 

    return v; 
} 

когда ваш convertView не нулевой добавить условие еще и получить ViewHolder экземпляр, который вы добавили

else { 
    holder = (ViewHolder) v.getTag(); 
} 
// now you would be feeding information to your `ImageView` and `TextView` 

holder.txtTitle.setText(locations.get(position).locName); 
holder.imageView.setImageBitmap(locations.get(position).locImage); 
+0

Это не поможет. Что-то очень странное случается, когда я отлаживаю, я вижу, что приложение никогда не достигает этого метода, это нормально? – user2367624

+0

нет, это ненормально, посмотрите на несколько примеров пользовательского списка, как работает пользовательский адаптер, попробуйте поставить журнал, где бы вы ни думали, необходимо проверить ход кода –

0

Если бы переопределить получить getCount() метод, как что:

@Override 
public int getCount(){ 
    return locations != null ? locations.size() : 0; 
} 
Смежные вопросы