How can i access fragment layout in parent activity?

961 views Asked by At

I have got a tabpager and fragments. And a frament has got a "GridView". I am using a basedapter innerclass in the fragment parent activity.

But when i want to set adapter to my gridview i m getting nullpointerexception. Because GridView variable is always null.how can solve this issue?

Fragment Parent MainActivity OnCreate Method;

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

Fragment 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 (For populate with adapter)

<?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>
2

There are 2 answers

5
Vaizadoo On BEST ANSWER

You cant acces fragment views like that, becouse they could be not yet in the activity view hierarchy.

You have to add some method to your fragment, like

myCustomFragment.setGridAdapter(MyCustomGridViewAdapter adapter)

and in this method in your custom fragment:

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

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

This code:

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

should be inside of your fragment's onCreateView. You should create fragments that are independent from the activity they're attached to.

If you absolutely need to access the fragment's layout from your activity you need to delay the findViewById because the fragment's layout is not yet inflated when you call it:

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

Although this code would work, I highly discourage you from using it!