簡體   English   中英

如何在父級活動中訪問片段布局?

[英]How can i access fragment layout in parent activity?

我有一個tabpager和片段。 而且一個frament有一個“ GridView”。 我在片段父活動中使用了基於適配器內部類

但是當我想為我的gridview設置適配器時,我會得到nullpointerexception 由於GridView變量始終為null。如何解決此問題?

片段父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>

您不能像這樣訪問片段視圖,因為它們可能尚未出現在活動視圖層次結構中。

您必須在片段中添加一些方法,例如

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 您應該創建獨立於其附加活動的片段。

如果您絕對需要從活動中訪問片段的布局,則需要延遲findViewById因為調用時片段的布局尚未膨脹:

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

盡管此代碼可以工作,但我強烈不鼓勵您使用它!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM