java - 如何访问父 Activity 中的 fragment 布局?

标签 java android android-fragments gridview baseadapter

我有一个分页器和 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/

相关文章:

android - 在 ViewPager 中只加载一个 Fragment

java - Spark java : how to handle multipart/form-data input?

java - 如何在java中读取带有属性的xml文件?

java - 即使编程为 MediaPlayer 也不会停止播放

java - Android 为什么我在为启动画面膨胀图层列表时出现错误

android - 带底部导航的导航组件

java - Spring web MVC 与 JAX WS 的互动

java - 添加jobStream实例

android - 在android中为多个像素更改图像png的颜色?

android - 如何从所有其他 fragment 导航到特定 fragment ?