0

我正在尝试使用在 Fragment 的布局findViewById()中查找一个RelativeLayout,然后将我的添加GridViewRelativeLayout. 这是我的代码:

RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
GridLayout gridLayout = new GridLayout(this);
relativeLayout.addView(gridLayout);

片段布局的 XML 文件:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.sepehr.dotsandlines.Game">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/relativeLayout">

    </RelativeLayout>
</FrameLayout>

错误:

原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.RelativeLayout.addView(android.view.View)”

注意:我在 MainActivity.java 中寻找 id 而不是 Fragment Java。

4

3 回答 3

0

内部Fragment首先使用 .Inside 方法获取root view并查找 id,然后使用以下findViewById().InsideonCreateView方法。

public View onCreateView(LayoutInflater inflater, 
                         ViewGroup container, 
                         Bundle savedInstanceState) {
     View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
RelativeLayout relativeLayout = (RelativeLayout)view. findViewById(R.id.relativeLayout);
     return view;
}
于 2018-06-28T20:32:17.670 回答
0

我自己想通了。首先,我在 MainActivity.java 文件中寻找 ID,onCreateView()onViewCreated()在 Game.java(片段 java 文件)中覆盖并没有做任何事情!那不是答案。

我曾经LayoutInflater膨胀 Fragment 的布局并使用它来查找 ID(objectCreate()由 activity_main 布局中的按钮调用)

public void objectCreate(View view){
   View v=inflater.inflate(R.layout.fragment_game, null, false);
   RelativeLayout relativeLayout = v.findViewById(R.id.relativeLayout);
   GridLayout gridLayout = new GridLayout(this);
   relativeLayout.addView(gridLayout);

   //adding some other views to the GridLayout

   //change layout to MainLayout.xml (Which contains the FrameLayout):
   v=inflater.inflate(R.layout.activity_main, null, false);
   v.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left));
   setContentView(v);
   //show the fragment:
   Class fragmentClass = Game.class;
   Fragment fragment = (Fragment) fragmentClass.newInstance();
   FragmentManager fragmentManager = getSupportFragmentManager();
   fragmentManager.beginTransaction().replace(R.id.fl, fragment).commit();
}

另一个问题是,我现在没有收到错误消息,但屏幕仍然是空白的,并且没有显示任何视图!

于 2018-06-29T08:11:43.823 回答
0

findViewById在 onCreateView中使用确实不是一个好主意。您可能会遇到无法找到视图的随机崩溃。

根据片段生命周期,您应该在onViewCreated

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// add your code here which executes after the execution of onCreateView() method.

}

更多细节可以参考Fragment 中 onCreateView 和 onViewCreated 的区别

于 2018-06-28T23:55:04.563 回答