我爲ListView和GridView創建了自定義適配器。這完全一樣,我只想要一個帶List的選項卡,另一個帶GridView。我可以將數據設置爲Fragment1上的ListView,但我無法對Fragment2上的GridView執行相同操作(提供空指針異常)。Android - 具有自定義適配器的GridView不起作用
代碼如下:
Fragment2.java:
public class FragmentTab2 extends Fragment {
GridView gridView;
Intent intent;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab2, container, false);
gridView = (GridView) rootView.findViewById(R.id.GridView1);
return rootView;
}
public GridView getGridView() {
return gridView;
}
}
CustomAdapter.java:
public class CustomAdapter extends BaseAdapter {
private ArrayList<ListData> data;
private Context context;
CustomAdapter(Context context, ArrayList<ListData> data) {
this.context = context;
this.data = data;
}
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View rowView = convertView;
if(rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.list_item, null);
}
ImageView image = (ImageView) rowView.findViewById(R.id.listLogo);
TextView nameVideo = (TextView) rowView.findViewById(R.id.label);
TextView link = (TextView) rowView.findViewById(R.id.link);
// Get individual object from ArrayList<ListData> and set ListView items
ListData temp_data = data.get(position);
image.setImageBitmap(temp_data.getImage());
nameVideo.setText(temp_data.getName());
link.setText(temp_data.getLink());
return rowView;
}
}
和主
ListView lw = fragmentTab1.getListView();
lw.setAdapter(new CustomAdapter(this, dataArray));
GridView gr = fragmentTab2.getGridView();
//gr.setAdapter(new CustomAdapter(this, dataArray));
註釋部分給出了空例外,其他一切都很好。有任何想法嗎? 謝謝。
android.app.FragmentManager fm = getFragmentManager();
android.app.FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_container, fragmentTab2);
ft.addToBackStack(null);
ft.commit();
能否請您提供完整的堆棧跟蹤? – 2014-11-23 22:00:29