在使用ListFragment的setEmptyText时报java.lang.IllegalStateException: Can't be used with a custom content view错误

今天搞了好久, 才基本解决了这个问题. 

 1 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     android:layout_width="match_parent"
 3     android:layout_height="match_parent" >
 4     
 5     <ListView 
 6         android:id="@android:id/list"  <!--这样命名我就不多说了-->
 7         style="@style/MyListView"
 8         android:layout_width="match_parent"
 9         android:layout_height="match_parent"/>
10 
11     <TextView 
12         android:id="@android:id/empty"  <!-- 为什么这样命名,且看下文 -->
13         android:layout_width="wrap_content"
14         android:layout_height="wrap_content"
15         android:layout_gravity="center"/>
16         
17 </FrameLayout>
//且看源码ListFragment


1
private void ensureList() { 2 if (mList != null) { 3 return; 4 } 5 View root = getView(); 6 if (root == null) { 7 throw new IllegalStateException("Content view not yet created"); 8 } 9 if (root instanceof ListView) { 10 mList = (ListView)root; 11 } else { 12 mStandardEmptyView = (TextView)root.findViewById(INTERNAL_EMPTY_ID); 13 if (mStandardEmptyView == null) { 14 mEmptyView = root.findViewById(android.R.id.empty); //且看这里 15 } else { 16 mStandardEmptyView.setVisibility(View.GONE); 17 } 18 mProgressContainer = root.findViewById(INTERNAL_PROGRESS_CONTAINER_ID); 19 mListContainer = root.findViewById(INTERNAL_LIST_CONTAINER_ID); 20 View rawListView = root.findViewById(android.R.id.list); 21 if (!(rawListView instanceof ListView)) { 22 if (rawListView == null) { 23 throw new RuntimeException( 24 "Your content must have a ListView whose id attribute is " + 25 "'android.R.id.list'"); 26 } 27 throw new RuntimeException( 28 "Content has view with id attribute 'android.R.id.list' " 29 + "that is not a ListView class"); 30 } 31 mList = (ListView)rawListView; 32 if (mEmptyView != null) { 33 mList.setEmptyView(mEmptyView); 34 } else if (mEmptyText != null) { 35 mStandardEmptyView.setText(mEmptyText); 36 mList.setEmptyView(mStandardEmptyView); 37 } 38 } 39 mListShown = true; 40 mList.setOnItemClickListener(mOnClickListener); 41 if (mAdapter != null) { 42 ListAdapter adapter = mAdapter; 43 mAdapter = null; 44 setListAdapter(adapter); 45 } else { 46 // We are starting without an adapter, so assume we won't 47 // have our data right away and start with the progress indicator. 48 if (mProgressContainer != null) { 49 setListShown(false, false); 50 } 51 } 52 mHandler.post(mRequestFocus); 53 }

在程序中重写

@Override
public void setEmptyText(CharSequence text) {
    TextView emptyView = (TextView)getListView().getEmptyView();
    emptyView.setVisibility(View.GONE);
    emptyView.setText(text);
}

然后就可以

setEmptyText(getString(R.string.list_no_data));

这样就成功了.

setEmptyText(CharSequence text) 只能用在ListFragment默认视图. 其背后还是用的ListView的setEmptyView()所以可以通过getEmptyView获取这个视图.

posted @ 2013-05-29 18:00  小草房Fang  阅读(2234)  评论(1编辑  收藏  举报