在Android中使用findViewById有困难怎么办?

4

我正在使用一些预生成的Android代码,但它没有起作用。

下面是片段的onCreateView函数:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_tabmain, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }

这段片段的xml代码如下:

<RelativeLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.startandselect.agora.tabmain$PlaceholderFragment">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

但是当我运行程序时,在textView.setText这一行出现错误,因为textView为空。 textView为空是因为它之前的代码未能找到该文本视图。 findViewById未能找到它,但我不知道原因。

我进行了调试,并发现真正的textView具有id:2131492994,而R.id.section_label的id为2131492997。


1
清理并重新构建项目。确保您正在使用正确的布局和正确的id。 - Karakuri
请确保 R.layout.fragment_tabmain 是您想要的那个,您可能已经复制并粘贴了它,因此此布局没有您的文本视图并将返回 null; - SaNtoRiaN
是的,我所做的就是清理和重建,然后它就正常工作了,谢谢。 - Tsangares
3个回答

5

尝试使用以下内容:

TextView textView = (TextView) findViewById(R.id.section_label);

改为:

TextView textView = (TextView) rootView.findViewById(R.id.section_label);

2
你在另一个活动布局中有相同的TextView android:id。

那不应该会有任何问题。只要您在同一布局文件中没有重复的Id,您就会做得很好... - Irshu

1

在评论中,Karakuri建议清理并重新构建。这是我尝试的第一件事,就解决了问题,谢谢。

解决方案:清理并重新构建项目。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接