2015-06-11 43 views
1

我有一个tabpager和碎片。一个Frament已经有了一个“GridView”。我在片段父代活动中使用基于内部类的我如何在家长活动中访问片段布局?

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

Fragment Parent MainActivity OnCreate Method;

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> 

回答

0

你不能ACCES这样的片段意见,becouse他们可以 尚未处于活动视图层次结构中。

你有一些方法添加到您的片段,像

myCustomFragment.setGridAdapter(MyCustomGridViewAdapter adapter) 

,并在此方法中自定义片段:

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

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

即使片段**可能不在活动的视图层次结构中,findViewById会在活动窗口中查找视图。因此,只要已经膨胀,您就可以从碎片中找到视图。 – Simas

+0

然后,我必须编写所有代码片段Java类我是否正确?或者有什么解决方案可以在mainactivity类中找到片段视图? –

+0

你想知道如果你需要实现自定义片段类吗? - 是的 – Vaizadoo

0

此代码:

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); 

尽管这段代码会工作,我强烈不鼓励你使用它!

+0

然后我必须在这里再次提问。我如何发送主活动上下文到片段类到我的适配器内部类? –

+0

@EmreErol你的意思是'getActivity()'? – Simas

+0

是的,谢谢。我处理它! –