2012-05-19 14 views
14

私はAsyncTasksからFragementsにアプリケーションを移植しています。ListFragmentどのようにlistViewを取得するには?

しかし、私のフラグメント内のlistView(id:list)要素にアクセスするにはどうすればよいですか?

class MyFragment extends ListFragment { 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View v = inflater.inflate(R.layout.list_fragment, container, false); 
     ListView listView = getListView(); //EX: 
     listView.setTextFilterEnabled(true); 
     registerForContextMenu(listView); 
     return v; 
    } 
} 

のxml:

 <ListView 
     android:id="@android:id/list" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" > 
    </ListView> 

例:onCreateViewドキュメントとして

Caused by: java.lang.IllegalStateException: Content view not yet created 
+0

http://stackoverflow.com/questions/9286391/android-why-is-this-telling-me-content-view-not-yet-created –

答えて

26

まま:

creates and returns the view hierarchy associated with the fragment 

ので、方法が戻らないため、あなたではないだろうにアクセスできるからgetListView()までです。 onActivityCreatedコールバックで有効な参照を取得できます。 ListViewが内部で宣言されている場合は、v.findViewById(android.R.id.list)を試してみることができますlist_fragment.xml

+1

私はonActivityCreateを使用してcontentviewを取得します100ミリ秒の待機時間を持つ遅延後の方法を使ってもクラッシュは発生しません – CQM

6

get listビューから見ると、より早く取得できます。

View view = inflater.inflate(android.R.layout.list_content, null); 
    ListView ls = (ListView) view.findViewById(android.R.id.list); 
    // do whatever you want to with list. 
3

代わりに、OnViewCreatedメソッドでListViewにアクセスできました。

+3

これは私にとって最も適切な解決策のようです。 the docsによると、onCreateView(LayoutInflater、ViewGroup、Bundle)が返された直後で、保存された状態がビューに復元される前に 'onViewCreated'が呼び出されます。これにより、サブクラスは、ビュー階層が完全に作成されたことを知った後、自分自身を初期化することができます。ただし、フラグメントのビュー階層は、この時点では親には関連付けられていません。 –

4

この問題の最も簡単で信頼性の高い解決策は、onActivityCreated()をオーバーライドすることです。あなたのリスト操作をそこで行います。

@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    ListView listView = getListView(); //EX: 
    listView.setTextFilterEnabled(true); 
    registerForContextMenu(listView); 
    super.onActivityCreated(savedInstanceState); 
} 
1
ListFragment listFrag = new ListFragment(){ 
     @Override 
     public void onViewCreated(View view, Bundle savedInstanceState) { 
      super.onViewCreated(view, savedInstanceState); 
      ListView list = getListView(); 
      // DO THINGS WITH LIST 
     } 
    }; 
関連する問題