我目前正在开发一个Android应用程序,它使用主屏幕上的导航标签。 选项卡1包含一个列表片段,该片段通过异步任务填充。但是,当我启动我的应用时,我只看到一个空白屏幕(see screenshot)。
问题是在异步任务完成之前创建了listfragment。 因此,只有在更改选项卡并重新选择选项卡1后才会显示列表中的信息。我是否可以以某种方式强制执行此操作而不实际单击选项卡?
我在onpostexecute()方法中尝试过几样的事情,例如在那里设置列表适配器,在适配器上调用notifyDataSetChanged()或调用片段的oncreate方法以某种方式刷新它 - 但没有成功。 我非常感谢任何帮助。提前谢谢!
相关代码段:
我的 Homescreen.class ,其中包含导航标签和填充列表的异步任务:
public class Homescreen extends ActionBarActivity implements ListListFragment.Callbacks {
public static ArrayList<Places> places = new ArrayList<Places>();
JSONObject obj = new JSONObject();
String tab_label1;
TabListener<ListListFragment> t1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new RetrievePlacesActivity().execute();
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tab_label1 = getResources().getString(R.string.tab_1);
Tab tab1 = bar.newTab().setText(tab_label1)
.setIcon(R.drawable.ic_action_view_as_list);
t1 = new TabListener<ListListFragment>(this, tab_label1,
ListListFragment.class);
tab1.setTabListener(t1);
bar.addTab(tab1);
// do the same with tab2 and tab3
Fragment.instantiate(this, ListListFragment.class.getName());
}
private class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
public TabListener(Activity activity, String tag, Class<T> cls) {
mActivity = activity;
mTag = tag;
mClass = cls;
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
ft.attach(mFragment);
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.detach(mFragment);
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
public class RetrievePlacesActivity extends
AsyncTask<Void, Integer, JSONArray> {
@Override
protected JSONArray doInBackground(Void... params) {
// Do a Http-Get Request and read the results into a JSONArray
JSONArray res = new JSONArray(result);
return res;
}
@Override
protected void onPostExecute(JSONArray jsonArray) {
// Get the JSON objects from jsonArray
// With the information of these objects create instances of class "Places"
// Add these places to an ArrayList called "places"
}
}
}
我的 ListListFragment.class 的一小部分访问了Homescreen.class中的ArrayList“places”并使用自定义适配器来填充listview:
public class ListListFragment extends ListFragment {
public interface Callbacks {
public void onItemSelected(String id);
}
public ListListFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PlacesAdapter adapter = new PlacesAdapter(getActivity(),
R.layout.list_line, Homescreen.places);
setListAdapter(adapter);
}
}