簡體   English   中英

如何在Android的片段中放入列表視圖?

[英]How to put a listview inside of a fragment in android?

我試圖在片段中放入一個簡單的listview。 按原樣運行時出現錯誤。 我沒想到它可以與當前的代碼一起使用,但是我不確定從這里開始。 任何幫助將不勝感激!

我的代碼:

public class Tab1Fragment extends ListFragment {

ListView listView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    LinearLayout theLayout = (LinearLayout) inflater.inflate(R.layout.tab1, container, false);
    listView = (ListView)theLayout.findViewById(R.id.ListView01);
    return theLayout;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Use an existing ListAdapter that will map an array
    // of strings to TextViews
    setListAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(),
            android.R.layout.simple_list_item_1, mStrings));
    getListView().setTextFilterEnabled(true);
}

private String[] mStrings = {
        "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
        "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
    };

}

我的運行時錯誤:

07-19 11:42:45.214: E/AndroidRuntime(19873): FATAL EXCEPTION: main
07-19 11:42:45.214: E/AndroidRuntime(19873): java.lang.RuntimeException: Unable to start activity ComponentInfo{package/package.TabActionBarActivity}: java.lang.IllegalStateException: Content view not yet created
07-19 11:42:45.214: E/AndroidRuntime(19873):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
07-19 11:42:45.214: E/AndroidRuntime(19873):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
07-19 11:42:45.214: E/AndroidRuntime(19873):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
07-19 11:42:45.214: E/AndroidRuntime(19873):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)

您應該嘗試在onActivityCreated()方法中調用setListAdapter() 這是因為Activity尚未完全由Fragment的onCreate()方法創建,因為每個生命周期都略有不同。

這是一個類似的問題: Android片段onCreateView與onActivityCreated

您的片段中有幾個問題:

  1. 如果您使用的是ListFragment,則在XML布局中,必須具有ID為“ android.R.id.list”的ListView。
  2. 在onViewCreated()而不是onCreate()中調用setListAdapter()方法。 這是因為在onCreateView()之前先調用onCreate()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM