Android Fragment和Listview适配器问题

时间:2014-09-03 19:15:25

标签: android listview android-fragments

我创建了一个包含listView:

的片段unity_view
<ListView
    android:id="@+id/listViewUnity"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginLeft="90dp"
    android:layout_toRightOf="@+id/firstName" >
</ListView>

以下代码(类扩展Fragment)生成一个空异常:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState) {

    // If activity recreated (such as from screen rotate), restore
    // the previous article selection set by onSaveInstanceState().
    // This is primarily necessary when in the two-pane layout.
    if (savedInstanceState != null) {
        mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
    }

    final ListView listview = (ListView) this.getActivity().findViewById(R.id.listViewUnity);
    String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
        "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
        "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux",
        "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2",
        "Android", "iPhone", "WindowsMobile" };

    final ArrayList<String> list = new ArrayList<String>();
    for (int i = 0; i < values.length; ++i) {
      list.add(values[i]);
    }
    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),
        android.R.layout.simple_list_item_activated_1);
    listview.setAdapter(adapter);

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.unity_view, container, false);
}

两个问题:

  1. 你知道为什么listview.setAdapter失败了吗?
  2. 我不应该在android.R.layout中选择 listViewUnity 作为选项吗?

2 个答案:

答案 0 :(得分:0)

首先,您无法找到android.R.layout.listViewUnity,因为android.R.layout是您无法修改的内部Android布局。相反,您可以使用R.layout.listViewUnity访问自己的布局。

您的ListView位于您的片段布局(unity_view.xml)中。要访问它 从代码开始,它首先需要膨胀:

View layout = inflater.inflate(R.layout.unity_view, container, false);
final ListView listview = (ListView) findViewById(R.id.listViewUnity);
// Do something else

return layout;

最后,当您创建适配器时,将活动作为上下文与项目一起传递,以便将它们填充到列表中:

final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
        android.R.layout.simple_list_item_1, list);

答案 1 :(得分:0)

您正试图从ListView获取Activity,但它位于Fragment的布局中。试试这个:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   View view = inflater.inflate(R.layout.unity_view, container, false);

   final ListView listview = (ListView) view.findViewById(R.id.listViewUnity);
   // Do something with your ListView

   return view;

}

据我所知,Android SDK中没有listViewUnity布局。