2012-12-04 58 views
3

我有一個活動的片段,其上有一個listview元素。無法將數據添加到列表視圖。有人能告訴我什麼是錯的嗎?將數據添加到片段的列表視圖

public class MainActivity extends FragmentActivity { 

    public String[] listS ={"item1","item2","item3"}; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     FragmentManager fm = getSupportFragmentManager(); 
     FragmentTransaction ft = fm.beginTransaction(); 
     MainFragment f = new MainFragment(); 
     ft.replace(R.id.fragcontainer, f); 
     ft.commit();  
     //here the problem occurs 
     ListView lv = (ListView)findViewById(R.id.listf); 
     lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_row,R.id.labeld, listS)); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 
} 

片段的類:

public class MainFragment extends Fragment { 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sis){ 
     return inflater.inflate(R.layout.fragment_layout, container, false); 
    } 

} 
+0

哪裏是你的'listf'元素的 「機器人」 盈?在'activity_main.xml'中? – fiddler

+0

不,在片段的佈局... – slyder07

+0

請參閱Brian的答案然後... – fiddler

回答

6

有許多用這種方法的問題,但它的根源在於FragmentTransactionreplace()方法補充說,我假定片段,包含了你ListView '試圖找到是一個異步過程。該片段不會被添加到活動的視圖層次立即但稍後一段時間。

如果你要的東西在Fragment添加到ListView,爲什麼不從MainFragment子類中的onCreateView()方法,而不是做呢?這就是它的工作原理。

編輯:典型onCreateView()

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_layout, container, false); 
    ListView lv = (ListView) view.findViewById(R.id.listf); 
    lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_row,R.id.labeld, listS));    
    return view; 
} 
+0

已經嘗試過,但是我無法在MainFragment子類中獲得對ListView的引用 – slyder07

+0

爲什麼?如何在'MainFragment'內創建佈局,以至於無法獲得對該佈局中的某些內容的引用? –

+0

當我試圖添加「ListView lv =(ListView)findViewById(R.id.listf)到MainFragment,findViewById函數是強調(我在Eclipse IDE中工作)... – slyder07

0

當U添加代碼的定義類,

public class MainFragment extends Fragment { 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sis) { 
      View view = inflater.inflate(R.layout.my_fragment, container, false); 
      ListView listView = (ListView) view.findViewById(R.id.list); 
      return view; 
     } 
    } 
0

的問題是,你問到活動中爲ListView控件

「this。」findViewById(...

你可以問這個片段查看或管理Fragment類中的listView內容。

0

請使用設計窗口中的列表視圖如下。我遇到了確切的問題,現在我可以在源代碼中找到視圖。

的主要問題是IDE的附加ID

<ListView 
    android:id="@+id/list" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 
</ListView> 
相關問題