返回數(shù)據(jù)到上一個activity/fragment
我的理解:首先,在源activity/fragment中進(jìn)行跳轉(zhuǎn)語句,并寫入一個request,跳轉(zhuǎn)后在跳轉(zhuǎn)的activity進(jìn)行返回數(shù)據(jù),寫入一個result,返回到源活動,然后在原活動進(jìn)行重寫onActivityResult方法,進(jìn)行接收匹配。
首先,基本思路是這樣,但是對于fragment和activity有些許區(qū)別,主要體現(xiàn)在:
跳轉(zhuǎn)activity
//setResult(RESULT_OK,intent);
//finish();
但是fragment中是沒有這個方法代碼的,又相應(yīng)的替換的代碼,
但是我i項目僅僅用到了activity向fragment傳值,所以沒有涉及到,而在源活動中,onActivityResult大致一樣,以下為我的部分代碼:
一:這是fragment向activity內(nèi)進(jìn)行跳轉(zhuǎn)
Button myButton = (Button) getActivity().findViewById(R.id.Add_Button);
myButton.setOnClickListener(new View.OnClickListener() {
? ?@Override
? ?public void onClick(View view) {
? ? ? ?Intent intent = new Intent(getActivity(), Add.class);
? ? ? ?Bundle bundle = new Bundle();
? ? ? ?bundle.putInt("User_id",User_id);
? ? ? ?intent.putExtras(bundle);
? ? ? ?//2023.5.16更改
? ? ? ?startActivityForResult(intent,1);
? ? ? ?// startActivity(intent);
? ?}
});
二:我跳轉(zhuǎn)回來的語句Intent intent = new Intent(Add.this, HomeFragment.class);
//更新操作 2023.5.16
System.out.println("comsumer ? ?=== ? " + comsumer);
intent.putExtra("already_Login",comsumer);
setResult(RESULT_OK,intent);
finish();
三:源活動接收的語句public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
? ? ? ?super.onActivityResult(requestCode, resultCode, data);
? ? ? ?if (requestCode == 1)
? ? ? ?{
? ? ? ? ? ?if(resultCode == RESULT_OK)
? ? ? ? ? ?{
? ? ? ? ? ? ? ?int flag = data.getIntExtra("already_Login",-1);
? ? ? ? ? ? ? // System.out.println("收到了 == " + data.getIntExtra("already_Login",-1));
? ? ? ? ? ? ? ?if(flag == -1)
? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ?Toast.makeText(getContext(), "出錯了,主人", Toast.LENGTH_SHORT).show();
? ? ? ? ? ? ? ?}else
? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ?Toast.makeText(getContext(), "收到了,主人", Toast.LENGTH_SHORT).show();
? ? ? ? ? ? ? ? ? ?User_id = flag;
? ? ? ? ? ? ? ? ? ?System.out.println("User_id " + User_id);
? ? ? ? ? ? ? ? ? ?simpleAdapter = new SimpleAdapter(getActivity(),getData(),R.layout.my_menu,new String[]{"type","money"},new int[]{R.id.myMenu_type,R.id.myMenu_money});
? ? ? ? ? ? ? ? ? ?listView.setAdapter(simpleAdapter);
? ? ? ? ? ? ? ?}
? ? ? ? ? ?}
? ? ? ?}
? ?}
?
原文鏈接:https://www.dianjilingqu.com/739398.html