2016-04-24 76 views
4

我正在使用一些预先生成的android代码,它不工作。遇到安卓系统的问题findViewById

下面是一个片段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有2131492997.

+1

清理并重建项目。确保你使用正确的布局和正确的ID。 – Karakuri

+0

确保'R.layout.fragment_tabmain'是你想要的,你可能已经复制并粘贴它,所以这个布局没有你的textview,并会返回null; – SaNtoRiaN

+0

是的,我所做的一切都是干净的和重建的,它很好地工作,谢谢你。 – Tsangares

回答

1

Karakuri在评论清理和重建建议。这是我尝试的第一件事,而这一切都花了,谢谢。

解决方案:清洁和重建项目。

2

一个id你有相同的机器人:在另一个活动布局的TextView的ID。

+0

这不应该导致任何问题。只要你在同一个布局文件中没有重复的ID,你就可以做得很好...... – Irshu

5

尝试使用以下命令:

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

代替:

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