我如何访问父 activity 中的片段布局?

How can i access fragment layout in parent activity?

我有一个tabpager和片段。一个框架有一个"GridView"。我在片段父 activity 中使用 basedapter 内部类

但是当我想为我的 gridview 设置适配器时,我得到 nullpointerexception。因为 GridView 变量总是 null.how 可以解决这个问题吗?

片段父 MainActivity OnCreate 方法;

GridView gv = (GridView)findViewById(R.id.gridview); // debugging and always null
gv.setAdapter(new AdapterB(this,WallPaperList)); 

片段xml

<!-- 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>

您不能像那样访问片段视图,因为它们可能还不在 activity 视图层次结构中。

你必须在片段中添加一些方法,比如

myCustomFragment.setGridAdapter(MyCustomGridViewAdapter adapter)

并在您的自定义片段中使用此方法:

public void setGridAdapter(){
    this.myCustomGridAdapter = adapter;
    GridView gv = (GridView)findViewById(R.id.gridview); 

    if(gv != null)
        gv.setAdapter(this.myCustomGridAdapter);
}

此代码:

GridView gv = (GridView)findViewById(R.id.gridview); // debugging and always null
gv.setAdapter(new AdapterB(this,WallPaperList)); 

应该在您片段的 onCreateView 内。您应该创建独立于它们所附加的 activity 的片段。

如果您确实需要从您的 activity 访问片段的布局,您需要延迟 findViewById 因为片段的布局在您调用它时尚未膨胀:

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        GridView gv = (GridView)findViewById(R.id.gridview);
        gv.setAdapter(new AdapterB(this, WallPaperList));
    }
}, 1000);

尽管此代码可以工作,但我强烈建议您不要使用它!