Android Fragment间通信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/QPC908694753/article/details/71171235
// 定义Fragment 理解为 是Activity的一部分
public class Fragment1 extends Fragment {

    // 当系统第一次画UI的时候调用 通过这个方法可以让Fragment显示自己的布局内容
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // 通过打气筒 把一个布局转换成一个View对象
        View view = inflater.inflate(R.layout.fragment_fragment1, null);

        //1 找到按钮 设置点击事件
        Button btn_update = (Button) view.findViewById(R.id.btn_update);
        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //2 修改fragment2里面的内容,通过fragment的公共桥梁--->Activity
                Fragment2 fragment2 = (Fragment2) getActivity().getSupportFragmentManager().findFragmentByTag("f2");
                fragment2.updateText("haha");
            }
        });
        return view;
    }
}

public class Fragment2 extends Fragment {

    private TextView tv_content;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fragment2, null);
        //1 找到tv
        tv_content = (TextView) view.findViewById(R.id.tv_content);
        return view;
    }
    // 修改TextView 的内容
    public void updateText(String content) {
        tv_content.setText(content);
    }
}

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //1 获取fragment管理者
        FragmentManager fragmentManager = getSupportFragmentManager();
        //2 开启一个事务
        FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
        //2.1 替换fragment
        beginTransaction.replace(R.id.ll_1, new Fragment1(), "f1");
        beginTransaction.replace(R.id.ll_2, new Fragment2(), "f2");
        //3 开启事务
        beginTransaction.commit();
    }
}

没有更多推荐了,返回首页