我有一个FragmentActivity
我添加一个ListFragment
到 using的FragmentTrasaction
. 一切都很好,但是我在尝试设置 中的 时遇到了“未创建内容视图”错误 ,onItemClickListener
如下所示:ListView
ListFragment
public class ContactList extends FragmentActivity implements
LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {
static private final String TAG = ContactList.class.getSimpleName();
private SimpleCursorAdapter mListAdapter;
ListFragment mListFrag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mListFrag = new ListFragment();
if (savedInstanceState == null) {
// add list view fragment
FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
ft.add(android.R.id.content, mListFrag);
ft.commit();
}
// set up list view adapter:
mListAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, null,
new String[] { ContactsContract.Contacts.DISPLAY_NAME },
new int[] { android.R.id.text1 },
SimpleCursorAdapter.NO_SELECTION);
// (we will switch in the cursor later)
mListFrag.setListAdapter(mListAdapter);
// set list view click listener:
// (THIS LINE, I KNOW NOW, CAUSES PROBLEMS - SO I MOVED IT
// TO onCreateView):
//mListFrag.getListView().setOnItemClickListener(this);
// initial cursor loader:
getSupportLoaderManager().initLoader(0, null, this);
}
我很快意识到我正在尝试调用getListView
该onCreate
方法,因此ListView
尚未显示。所以,我把setOnItemClickListener
线移到onCreateView
:
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
View v = super.onCreateView(name, context, attrs);
// set list view click listener:
mListFrag.getListView().setOnItemClickListener(this); // this still crashes
return v;
}
不幸的是,这仍然会因“尚未创建内容视图”错误而崩溃。我不明白这一点 - 在调用super.onCreateView
所有视图之后肯定现在应该已经创建了吗?
我终于inItemClickListener
通过将它放在“onResume()”上来工作,但我不知道为什么它在onCreateView
.
任何人都可以启发我吗?
谢谢。