我为ListView和GridView创建了一个自定义适配器。它完全相同,我只想要一个带有List的选项卡,另一个带有GridView。我可以在Fragment1上将数据设置为ListView,但我不能对Fragment2上的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));
评论部分给出Null Exception,其他一切都很好。有任何想法吗? 感谢。
android.app.FragmentManager fm = getFragmentManager();
android.app.FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_container, fragmentTab2);
ft.addToBackStack(null);
ft.commit();
答案 0 :(得分:0)
看起来fragmentTab2.getGridView();
返回null。
确保fragmenttab2
中的GridView实际上具有ID GridView1
。
答案 1 :(得分:0)
我认为dataArray的问题可能是第一个适配器尝试在网格中设置单独的数组并检查