我有一个分页器和 fragment 。框架有一个“GridView”。我在 fragment 父 Activity 中使用basedapter内部类。
但是当我想将适配器设置为我的 gridview 时,我得到了 nullpointerexception。因为GridView变量始终为null。如何解决这个问题?
Fragment父MainActivity OnCreate方法;
GridView gv = (GridView)findViewById(R.id.gridview); // debugging and always null
gv.setAdapter(new AdapterB(this,WallPaperList));
XML fragment
<!-- TODO: Update blank fragment layout -->
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
MyGrid.xml(用于填充适配器)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/imagepart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Seç"
android:id="@+id/checkBox" />
</LinearLayout>
最佳答案
您无法像这样访问 fragment View ,因为它们可能尚未位于 Activity View 层次结构中。
您必须向 fragment 添加一些方法,例如
myCustomFragment.setGridAdapter(MyCustomGridViewAdapter adapter)
并在您的自定义 fragment 中的此方法中:
public void setGridAdapter(){
this.myCustomGridAdapter = adapter;
GridView gv = (GridView)findViewById(R.id.gridview);
if(gv != null)
gv.setAdapter(this.myCustomGridAdapter);
}
关于java - 如何访问父 Activity 中的 fragment 布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30783042/