樓主最近在學習安卓,用和ListView類似的方法實現Gridview的時候出現了問題。希望高手能指點一二。
aty_using_gridview.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">
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/gridView"
android:numColumns="3"/>
</LinearLayout>
grid_view_cell.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/img_grid_view" />
</FrameLayout>
這個是Activity
public class AtyUsingGridView extends Activity {
private GridView gridView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aty_using_gridview);
ImageGridViewAdapter adapter=new ImageGridViewAdapter(this);
gridView.findViewById(R.id.gridView);
gridView.setAdapter(adapter);
}
}
這個是adapter
public class ImageGridViewAdapter extends BaseAdapter {
private Context context=null;
private ImageGridViewData data[]= {
new ImageGridViewData( R.drawable.img2),
new ImageGridViewData(R.drawable.img2),
new ImageGridViewData( R.drawable.img2),
};
public ImageGridViewAdapter(Context context){
this.context=context;
}
public Context getContext() {
return context;
}
@Override
public int getCount() {
return data.length;
}
@Override
public ImageGridViewData getItem(int i) {
return data[i];
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
FrameLayout fl=null;
if(view!=null){
fl=( FrameLayout)view;
}else{
fl= ( FrameLayout) LayoutInflater.from(getContext()).inflate(R.layout.grid_view_cell,null);
}
ImageGridViewData data=getItem(i);
ImageView imgID=(ImageView)fl.findViewById(R.id.img_grid_view);
imgID.setImageResource(data.imgID);
return fl;
}
}
運行出現錯誤如下
Unable to start activity
java.lang.NullPointerException
我這有什麼錯誤,希望高手給指出啊,萬分感謝。
gridView.findViewById(R.id.gridView); 這裡你沒有實例化gridview
改為gridview = gridView.findViewById(R.id.gridView)