【发布时间】:2015-06-17 18:53:42
【问题描述】:
我是新来的。我有一个用于片段集合对象的 XML。在我有两个完美运行的文本视图。当我尝试以完全相同的格式添加另一个时,接收无法解决错误。 (即:android:id="@android:id/tvNewText")。 如果我添加一个像常规 XML 一样的 id(即:android:id="@+id/tvAnotherNewText"),我无法从我的 Fragment onCreateView 访问它。有什么帮助吗? fragment_collection_object.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@android:id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="40sp"
android:padding="32dp"
android:text="Sports Bar" />
这工作正常,但在它的正下方,我添加了一个新的 TextView,它无法解析 id。
<TextView
android:id="@android:id/tvNewText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Some Words" />
尝试从以下代码访问:
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText((args.getString(ARG_OBJECT)));
((TextView) rootView.findViewById(android.R.id.tvNewText)).setText("heyo");
return rootView;
}
}
这里的 text1 工作正常且符合预期,但无法在 tvNewText 上解决。提前感谢您的帮助。
【问题讨论】:
-
tvNewText听起来像一个自定义标识符。在您的 TextView 中使用android:id="@+id/tvNewText",而onCreateView使用findViewById(R.id.tvNewText) -
这对我不起作用,可能是因为 DemoObjectFragment 是静态的。如果我离开,(TextView)rootView.find(....) 那么它就找不到 tvNewText。此外,这个想法并不能解释为什么 text1 有效。
-
如果找不到,说明它不是fragment_collection_object.xml的一部分
-
嗯,这就是我的困惑所在。我不明白为什么它可以找到 text1 而不是 tvNewText。它们的添加完全相同。 (到 fragment_collection_object.xml)
-
已解决,谢谢 Blackbelt。我仔细阅读并没有意识到我还有'android.R.id'。我改变了,它工作。我仍然不完全理解为什么第一个文本视图有效而不是第二个。
标签: android xml android-fragments