使用“FindviewById”时返回null+;id";但是当我们使用Android:id时就可以了
我正在为片段创建一个示例应用程序。 我已经创建了一个片段并从中渲染视图。 但是,当我在布局中使用使用“FindviewById”时返回null+;id";但是当我们使用Android:id时就可以了,android,android-layout,android-fragments,Android,Android Layout,Android Fragments,我正在为片段创建一个示例应用程序。 我已经创建了一个片段并从中渲染视图。 但是,当我在布局中使用android:id=“@+id/text2”时,应用程序试图呈现视图时崩溃 <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/content" android:l
android:id=“@+id/text2”
时,应用程序试图呈现视图时崩溃
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/text2"
style="?android:textAppearanceLarge"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below ="@id/text2"
android:inputType="textPersonName"
android:text="FIR Number"
android:ems="10"
android:layout_centerHorizontal="true"
android:id="@+id/editText"
tools:layout_marginTop="10dp"
style="@android:style/Widget.EditText"
android:textAlignment="center" />
</RelativeLayout>
</ScrollView>
对于这两种情况,片段视图中的代码都是不变的
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout containing a title and body text.
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_accident_details_step1, container, false);
// Set the title view to show the page number.
((TextView) rootView.findViewById(android.R.id.text2)).setText(getString(R.string.title_template_step, mPageNumber + 1));
return rootView;
}
为什么它在一种情况下有效,而在另一种情况下无效?有人能帮忙吗?您需要使用
R.id.text2
指向R
文件中生成的id
使用@+id/
,阅读更多内容,并阅读有关访问平台资源的内容
所以使用
((TextView) rootView.findViewById(R.id.text2)).setText(getString(R.string.title_template_step, mPageNumber + 1));
// ^^^^^^^^^^
您正在片段中使用android id
((TextView) rootView.findViewById(android.R.id.text2)).setText(getString(R.string.title_template_step, mPageNumber + 1));
更改为
((TextView) rootView.findViewById(R.id.text2)).setText(getString(R.string.title_template_step, mPageNumber + 1));
android.R是错误的。它调用android包的ID,而不是您在项目中创建的ID。所以在“R”之前删除“android”,非常感谢。这肯定会有所帮助。
((TextView) rootView.findViewById(R.id.text2)).setText(getString(R.string.title_template_step, mPageNumber + 1));