问题描述
我有一个打开新活动的片段.当用户单击后退"按钮时,如何将数据传递回该活动的片段?我尝试创建一个新的 Intent
并将数据放入其中,然后调用 setResult()
,但是 Fragment
或 FragmentActivity
中的 onActivityResult
中包含任何内容.我现在唯一能想到的方法是通过静态方法,但仍然想看看是否有适当的方法来做到这一点?
I have a fragment that opens up a new activity. how can I pass data back to the fragment from that activity when user clicks on back button?I've tried creating a new Intent
and put data in there then call setResult()
, but neither the Fragment
or FragmentActivity
got anything in onActivityResult
. the only way I can think of now is through static method, but still want to see if there's a proper way of doing this?
谢谢!
推荐答案
调用静态函数并分配不是正确的解决方案.您可以使用接口回调,也可以使用startActivityForResult()方法.
calling static function and assigning is not a proper solution. you can use interface call back or you can use startActivityForResult() method.
界面回调的基本思想;
interface callback basic idea ;
public class YourActivity extends Activity{
private MyListener mFragmentCallbackListener;
public YourActivity(MyListener listener){
mFragmentCallbackListener = listener;
}
@Override
public void onBackPressed(){
if(mFragmentCallbackListener != null){
mFragmentCallbackListener.updateFragment(String data);
}
}
public interface MyListener{
void updateFragment(String data)
}
}
这篇关于当用户单击Android中的“后退"按钮时,如何将数据从活动发送到片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!