0
我想要使用ListView和片段。片段和列表視圖
我的代碼:
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
您調試了嗎?在適配器構造函數中是否有NULL值?顯然這不是值,我非常懷疑它的android.R.layout.simple_list_item_1,所以我的猜測會是getActivity()是NULL –
是的它是空的。現在我已經安裝了它,但它仍然是空的? – ternes3
您是否嘗試過由Karakuri發佈的解決方案? –