使用 Fragment 时 findViewById 返回 NULL [英] findViewById returns NULL when using Fragment

查看:30
本文介绍了使用 Fragment 时 findViewById 返回 NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Android 开发新手,当然也是 Fragments.

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

我想在主要活动中访问我的片段的控件,但findViewById"返回 null.没有片段,代码工作正常.

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

这是我的代码的一部分:

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 为空.

我的代码中缺少什么或我应该怎么做?

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

推荐答案

你应该在FragmentonCreateView方法上inflate片段的布局code> 然后你可以简单地使用 findViewById 在你的 Activity 上访问它的元素.

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,所以我将 inflate 结果转换为 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;
        }
    }

这篇关于使用 Fragment 时 findViewById 返回 NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆