我有一个关于 Activity 的 fragment ,上面有一个 ListView 元素。无法将数据添加到 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;
}
}
fragment 的类:
public class MainFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sis){
return inflater.inflate(R.layout.fragment_layout, container, false);
}
}
最佳答案
此方法存在许多问题,但其根源在于 FragmentTransaction
replace()
方法添加了 fragment ,我假设该 fragment 包含ListView
您要查找的是一个异步进程。该 fragment 不会立即添加到 Activity 的 View 层次结构中,而是在一段时间后添加。
如果您想向 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;
}
关于android - 将数据添加到 fragment 的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13703028/