我有一个带有片段的应用程序。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
view=inflater.inflate(R.layout.my_list_view, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
RequestManager.getInstance(getActivity()).doRequest().Populate();
// This is Android Volley HTTP Request Manager (using RequestProxy.java)
// Inside Populate() I use activity.findViewById(R.id.myList), which is the list in the xml.
// activity is MainActivity I passed to the RequestManager above.
}
更新:添加填充方法。
public class RequestProxy {
public Activity activity;
public void Populate(){
JsonArrayRequest JsonRequest = new JsonArrayRequest(feed_url, new Response.Listener<JSONArray> () {
@Override
public void onResponse(JSONArray aJsonResponse) {
// -----------
// ... I work here with the response to match format, etc...
// -----------
// Populate list with response
CustomAdapter listAdapter = new CustomAdapter(activity,MyArray,1);
ListView myList = (ListView) activity.findViewById(R.id.myList);
Log.e("myList is Null", String.valueOf(myList == null)); // Null the second time, not the first.
if(myList!=null) myList.setAdapter(newsAdapter);
}
}, new Response.ErrorListener() {
// Irrelevant...
});
}
}
}我第一次运行该应用程序(安装后立即)它工作得很好。然后,如果我通过按返回按钮 ( finish() ) 退出并再次启动应用程序,findViewById(R.id.myList)
返回 null。
只有当我在onDestroy()
方法中使用android.os.Process.killProcess(android.os.Process.myPid());
时,应用程序下次才能正确启动。
事实:
- 第二次启动应用程序时,
onCreateView
被正确调用。 -
view
第二次也正确充气。 - 如果我在
onActivityCreated
内部进行findViewById(R.id.myList)
,则它不为空。只有当我从 Populate() 调用它时,它才会返回 null。
所以。。。
为什么它在第一时间有效,而不是第二时间?
为什么在 Populate() 中第二次丢失活动引用?
更新:经过一些调试,我发现活动引用并没有丢失。我不能只参考片段的视图。
如何让 Popuplate() 从外部类引用片段上的视图。类似于MainActivity.fragment1.view的东西。
旁注:我使用了超过 1 个片段(我只是在这里总结这个想法)。
那是很久以前的事了,但我遇到了同样的问题,下面的文章解决了这个问题作为一个魅力。.
https://www.bignerdranch.com/blog/solving-the-android-image-loading-problem-volley-vs-picasso/