我正在尝试使用 ListView 和 Fragment。
我的代码:
public static class ownFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyListFragment test = new MyListFragment();
test.makelist();
return inflater.inflate(R.layout.whitelist_content, container, false);
}
public class MyListFragment extends ListFragment {
private AdapterView.OnItemClickListener listener;
public void makelist()
{
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
public void setOnItemClickListener(AdapterView.OnItemClickListener l) {
this.listener = l;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if(listener != null) {
listener.onItemClick(l, v, position, id);
}
}
}
}
public void clickme(View view){
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new ownFragment())
.commit();
}
但所以我得到一个 NullPointerException
enter code her07-26 22:57:46.709 19489-19489/de.anocom.ecp E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
at de.anocom.ecp.MainActivity$Whitelist$MyListFragment.makelist(MainActivity.java:296)
at de.anocom.ecp.MainActivity$ownFragment.onCreateView(MainActivity.java:282)
at android.app.Fragment.performCreateView(Fragment.java:1695)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
at android.app.BackStackRecord.run(BackStackRecord.java:682)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)e