我正在学习如何使用ListFragment,并且应用程序在运行以下代码时崩溃:
public class profileListFragment extends ListFragment {
String[] countries = new String[] {"USA", "China"};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(),
android.R.layout.simple_list_item_1,countries);
setListAdapter(adapter);
View retView = super.onCreateView(inflater, container, savedInstanceState);
return retView;//super.onCreateView(inflater, container, savedInstanceState);
}
public void onListItemClick(ListView I, View v, int position, long id){
I.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
I.setSelector(android.R.color.holo_blue_light);
}
}
我知道这是因为getListView()语句,因为当我删除它时它不会崩溃......
任何帮助非常感谢
I/ActivityManager(352): START {cmp=myapp.app/.loadProfile u=0} from pid 24295
E/AndroidRuntime(24295): java.lang.RuntimeException: Unable to start activity ComponentInfo{myapp.app/myapp.app.loadProfile}: android.view.InflateException: Binary XML file line #6: Error inflating class fragment
E/AndroidRuntime(24295): at myapp.app.loadProfile.onCreate(loadProfile.java:12)
E/AndroidRuntime(24295): at myapp.app.profileListFragment.onCreateView(profileListFragment.java:19)
11-10 22:15:01.002: W/ActivityManager(352): Force finishing activity myapp.app/.loadProfile
答案 0 :(得分:0)
我制作了一个看起来像这样的xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice" >
</ListView>
</LinearLayout>
然后给它充气并在该视图上执行findViewById寻找android.R.id.list,然后在第一时间使用我需要的ListView处理程序。代码片段是这样的:
View retView = inflater.inflate(R.layout.fragment_load_profile_list_layout,container, false);
ListView lv = (ListView) retView.findViewById(android.R.id.list);
lv.setSelector(android.R.color.holo_blue_light);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);