默认情况下,我在创建家庭片段启动时有一个导航抽屉。现在从我的主要活动中,我进入下一个活动,我执行一些操作并使用onActivityResult返回mainactivity。在片段中获取活动结果
高兴在这里一切工作正常。这是我的问题。
我在我的HomeFragment中有一个listview,所以在onActivityResult中,我得到了在其他活动中执行的值。现在我如何将这些值传递给我的主页片段。
这是我从mainactivity推出新的活动:
Intent i = new Intent(MainActivity.this, AddTask.class);
startActivityForResult(i,1);
现在在AddTask我做一些操作,并发送回主要活动如下所示:
Intent i = new Intent(AddTask.this,MainActivity.class);
setResult(RESULT_OK, i);
finish();
现在在我的MainActivity onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
AddedTask = data.getStringExtra("NewTask");
CategoryName= data.getStringExtra("CategoryItem");
TaskTime=data.getStringExtra("TaskTime");
SharedPreferences settings = getSharedPreferences("taskdetails",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("NewTask", AddedTask);
editor.putString("CategoryItem", CategoryName);
editor.putString("TaskTime", TaskTime);
editor.commit();
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
现在我在我的HomeFragment中有一个listView,其中I需要更新这些值:
public class HomeFragment extends Fragment {
ListView lv;
static final String TAG ="HomeFragment";
private AdapterListViewData adapterListViewData;
private ArrayList<DataShow> listData = new ArrayList<DataShow>();
private ListView listViewData;
String CategoryName,TaskTime;
String AddedTask;
public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
listViewData = (ListView)rootView.findViewById(R.id.listViewData);
SharedPreferences settings = this.getActivity().getSharedPreferences("taskdetails",
Context.MODE_PRIVATE);
AddedTask = settings.getString("NewTask",null);
CategoryName= settings.getString("CategoryItem",null);
TaskTime=settings.getString("TaskTime",null);
listData.add(new DataShow(AddedTask,CategoryName,TaskTime));
adapterListViewData = new AdapterListViewData(getActivity().getBaseContext(),listData);
adapterListViewData.notifyDataSetChanged();
return rootView;
}
}
我没有收到任何错误,并且没有显示listview。请告诉我。
@ downvoter护理的人发表意见 – coder
我已经发布了2个回答。我认为我使用newInstance()的最新版本足以满足您的需求。 –