如何从父Activity中的onActivityResult()更新Fragment视图

时间:2017-07-05 08:36:10

标签: android broadcastreceiver fragment

在我的Activity中,我实现了onActivityResult:

@Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            //do something

        }

我尝试在Fragment中实现onActivityResult:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10020) {
            Log.e(TAG, "requestCode == 10020");
            tv1.setText(Html.fromHtml("You are currently on a <b>GOLD</b> plan. You can:"));
        }
        Log.e(TAG, "line 401");

    }

和BroadcastReceive,在父Activity中到达onActivityResult时将被调用,但它们都不起作用。我怎样才能做到这一点?救救我!

1 个答案:

答案 0 :(得分:0)

在你的片段中声明一个公共方法,它接收所有必需的信息来更新视图(某些文本?)。当您在活动中创建片段时,请保留对它的引用,以便您可以调用该方法。

活动

MyFragment fragment;

oncreateView() {
    if(savedInstance == null) {
        fragment = // create fragment
        // getSupportFragmentManager() and add it to the activity 
    }
}

onActivityResult() {
    fragment.updateText(String text);
}

片段

public class MyFragment {
    ...
    ...
    public void updateText(String text) {
        // update the textview with the new text
    }
}