在我的应用程序中,我有一个标签布局(共4个),每个标签包含一个由ViewPagerAdapter管理的ListFragment,我想要做的是在活动时更新其中一个ListFragment的内容(在操作栏)完成,并可能将焦点设置在右侧选项卡上。
我已经搜索了一个解决方案,我找到了这个:update ListFragment when Activity finishes,但似乎在我的情况下不起作用。
在我使用的MainActivity中启动活动(添加用户以在列表中显示的活动):
Intent intent = new Intent(this, CreateUser.class);
startActivityForResult(intent, 101);
在我设置的CreateUser活动结束时:
setResult(Activity.RESULT_OK);
finish();
在ListFragment类中:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == MYACTIVITY_REQUEST_CODE) && (resultCode == Activity.RESULT_OK)){
((BaseAdapter)adapter).notifyDataSetChanged();
}
}
但是当活动结束时没有任何事情发生,因为从不调用onActivityResult。我该怎么办?
编辑:增加了最佳理解课程
CreateUser.java
public class CreateUser extends AppCompatActivity {
//The user creation process is done inside class ProcessCreateUser
//that extend AsycTask
private class ProcessCreateUser extends AsyncTask<String, String, JSONObject> {
//...
//onPreExecute, doInBackground
//...
@Override
protected void onPostExecute() {
super.onPostExecute();
//db op...
//at this point the db is updated with the new user and close the activity
finish();
}
}
public void onDestroy(){
Tab3.updateFragmentList();
}
}
Tab3.java (ListFragment类)
public class Tab3 extends ListFragment implements Observer
{
//in onActivityCreated(Bundle savedInstanceState) i get the data from the db and set the adapter
@Override
public void update(Observable observable, Object data) {
}
public static void updateFragmentList() {
//problem: i can't get the adapter from a static function
//but this must be static for be called from CreateUser
((BaseAdapter)adapter).notifyDataSetChanged();
}
}
答案 0 :(得分:0)
我认为你可以使用Observer模式。例如:
public interface Observer {
public void updateFragmentList();
}
public class YourFragment extends Fragment implement Observer {
public void updateFragmentList() {
// You do some magic code here, such as:
// Update your data for each FragmentList
}
}
public class YourActivity extends Activity {
private ArrayList<Observer> observers = new ArrayList<Observer>();
public void onCreate() {
// Here you add all FragmentList to observers
}
public void onDestroy(){
for(Observer ob in observers) {
ob.updateFragmentList();
}
}
}
答案 1 :(得分:0)
我终于得到了它(没有Observer),我已经将onActivityResult方法从ListFragment移动到MainActivity,在ListFragment中我已经为所有更新作业添加了一个简单的public void updateView()方法。列表,我已将以下方法添加到ViewPagerAdapter中以调用updateView()方法:
@Override
public int getItemPosition(Object object) {
if (object instanceof Tab3) {
((Tab3) object).updateView();
}
return super.getItemPosition(object);
}