我使用以下代码在片段中使用listview。我不知道为什么它不起作用?
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
SharedPreferences allcontactssharedpreferences = getActivity().getSharedPreferences("ALL_LIST_FOR_CONTROL", Context.MODE_PRIVATE);
Map<String,?> keys = allcontactssharedpreferences.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Toast.makeText(getActivity(),entry.getKey(),Toast.LENGTH_LONG).show();
if ( entry.getKey() != null)
AllContacts.add(entry.getKey());
}
listView = (ListView)view.findViewById(R.id.theListOfHistoryControl);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,AllContacts);
listView.setAdapter(adapter);
return view;
}
我尝试了下面的解决方案,但它也没有工作:List View in Fragment not working
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
SharedPreferences allcontactssharedpreferences = getActivity().getSharedPreferences("ALL_LIST_FOR_CONTROL", Context.MODE_PRIVATE);
Map<String,?> keys = allcontactssharedpreferences.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Toast.makeText(getActivity(),entry.getKey(),Toast.LENGTH_LONG).show();
if ( entry.getKey() != null)
AllContacts.add(entry.getKey());
}
// listView = (ListView)view.findViewById(R.id.theListOfHistoryControl);
//
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,AllContacts);
//
// listView.setAdapter(adapter);
return view;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
listView = (ListView)view.findViewById(R.id.theListOfHistoryControl);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,AllContacts);
listView.setAdapter(adapter);
}
请帮帮我。
编辑1:fragment_home.xml是:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.shiza.callhistorycontrol.Home">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/theListOfHistoryControl" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/theListOfHistoryControl">
</ListView>
</LinearLayout>