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

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

问题描述

我是新来的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;
        }
    }

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

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