gpt4 book ai didi

Android Fragment - BroadcastReceiver调用 fragment 方法

转载 作者:太空宇宙 更新时间:2023-11-03 11:36:49 25 4
gpt4 key购买 nike

我有一个 BroadcastReceiver,它接收发送到 Fragment 的广播。我正在接收广播,但如何从 Fragment 本身调用方法?我基本上需要在广播到达后更新一个列表,列表和更新方法是 fragment 的一部分。

public class FragmentReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action != null && action.equals("AllTasksFragmentUpdate"))
{
//
}
}
}

注册接收器:

    @Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getActivity().registerReceiver(new FragmentReceiver(), new IntentFilter("AllTasksFragmentUpdate"));
}

如何从 fragment 中调用方法?

最佳答案

您可以通过以下方式实现您的广播接收器:

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.adobe.libs.connectors.R;

public class YourFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
//Start listening for refresh local file list LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mYourBroadcastReceiver,
new IntentFilter(<YOUR INTENT FILTER>));

return inflater.inflate(R.layout.your_fragment_layout, null, true);
}

@Override
public void onDestroyView() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mYourBroadcastReceiver);
}

private final BroadcastReceiver mYourBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Now you can call all your fragments method here
}
};
}

关于Android Fragment - BroadcastReceiver调用 fragment 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35996963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com