从片段到Activity的调用方法 [英] call method from fragment to Activity

查看:52
本文介绍了从片段到Activity的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有活动,并且我根据应用程序业务调用了许多片段,我需要从活动中的片段中调用方法,我在互联网上进行了搜索,但找不到解决方法

hello i have activity and i call many fragment based on my application business i need to call method from fragment in activity i searched in the internet but i cannot find the solution

这是我的片段:

public class HomeFragment extends Fragment implements View.OnClickListener {
public HomeFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Log.d("onCreate", "onCreateViewHF");
        view = inflater.inflate(R.layout.new_fragment_home, container, false);
}

/// this method i need to call in Activity 
 public void addUserLineInfoFragment() {
        userLineInfoFragment = new UserLineInfoFragment();
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.replace(R.id.user_info_fragment_container, userLineInfoFragment).commit();
        Log.d("HOMMETEST","HOMMMME");
    }

推荐答案

从片段中调用Activity的方法

 ((YourActivityName)getActivity()).addUserLineInfoFragment();

从活动"中调用片段的方法

1.创建界面

 public interface OnButtonListener
    {
        void onButtonClick();
    }

2.在活动中初始化

 protected OnButtonListener onActionButtonListener;

    public void setOnButtonListener(OnButtonListener actionButtonListener)
    {
        this.onActionButtonListener = actionButtonListener;
    }

3.在活动"中,单击需要执行此操作时的事件

this.onActionButtonListener.onButtonClick();

4.在片段中实现监听器(OnButtonListener)

 @Override
    public void onButtonClick(){}

5.片段onCreateView

((YourActivityName) getActivity()).setOnButtonListener(this);

这篇关于从片段到Activity的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆