使用片段时findViewById返回NULL片段、findViewById、NULL

2023-09-12 04:35:13 作者:善解人意

我是新来的Andr​​oid开发课程片段的和。

I'm new to Android developing and of course on Fragments.

我要访问的主要活动我片段的控制,但findViewById'返回null。 无片段code正常工作。

I want to access the controls of my fragment in main activity but 'findViewById' returns null. without fragment the code works fine.

下面是我的code部分:

Here's part of my code:

在片段

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:ignore="HardcodedText" >

    <EditText
        android:id="@+id/txtXML"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:ems="10"
        android:scrollbars="vertical">
    </EditText>

</LinearLayout>

MainActivity的OnCreate:

the onCreate of MainActivity:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.main);

        this.initialisePaging();

        EditText txtXML = (EditText) findViewById(R.id.txtXML);}

在这一点上的 txtXML 为空。

缺了什么在我的code或我应该怎么办?

What's Missing in my code or what should I do?

推荐答案

您应该膨胀片段上的布局 onCreateView 的方法片段,那么你可以简单地访问它是在你使用 findViewById 活动

You should inflate the layout of the fragment on onCreateView method of the Fragment then you can simply access it's elements with findViewById on your Activity.

在本例中我的片段布局是一个LinearLayout中,所以我投了膨胀结果来的LinearLayout。

In this Example my fragment layout is a LinearLayout so I Cast the inflate result to LinearLayout.

    public class FrgResults extends Fragment 
    {
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        {
            //some code
            LinearLayout ll = (LinearLayout)inflater.inflate(R.layout.frg_result, container, false);
            //some code
            return ll;
        }
    }