【发布时间】:2014-09-15 19:27:54
【问题描述】:
我有一个在互联网上似乎很常见的问题:我创建了一个只有一个片段的活动。这是生成的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
ListView lv = (ListView) findViewById(android.R.id.list);
}
}
在条件之后或内部,我无法使用 findViewById 获取任何对象:它始终为空。这是生成的其余代码:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_customer,
container, false);
return rootView;
}
activity_customer.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.axacs.marc.CustomerActivity"
tools:ignore="MergeRootFrame" />
列表视图实际上在 fragment_customer.xml 中:
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/new_folder_button"
android:text="" />
有人知道缺少什么吗?
【问题讨论】:
-
Listview 属于
fragment_customer.xml.post 一样 -
干净构建你的项目。显示您的 activity_customer.xml
-
ListView lv = (ListView) findViewById(android.R.id.list);在片段 onCreateView() 上移动这条线
-
View rootView = inflater.inflate(R.layout.fragment_customer,container, false); ListView lv = (ListView) rootView.findViewById(android.R.id.list); return rootView; -
非常感谢。我不习惯碎片,但似乎我的问题很简单。我在使用 viewpager 时遇到了同样的问题,但您的解决方案在这种情况下不起作用。如果它一直困扰着我,我会发布另一个问题。再次感谢您!
标签: android android-fragments nullpointerexception findviewbyid