首页 > 学院 > 开发设计 > 正文

Fragment之间的通信

2019-11-06 09:49:31
字体:
来源:转载
供稿:网友
package com.itheima74.fragmentpassvalue;import android.app.FragmentManager;import android.app.FragmentTransaction;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;/** * 两个Fragment之间传值 * 公共桥梁----MainActivity */public class MainActivity extends AppCompatActivity { @Override PRotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.fl1, new Fragment1(), "fl1"); transaction.replace(R.id.fl2, new Fragment2(), "fl2"); transaction.commit(); }}package com.itheima74.fragmentpassvalue;import android.app.Fragment;import android.os.Bundle;import android.support.annotation.Nullable;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Toast;/** * Created by My on 2017/2/27. */public class Fragment1 extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment1, null); view.findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 修改Fragment2中Textview的值 Fragment2 fragment2 = (Fragment2) getActivity().getFragmentManager().findFragmentByTag("fl2"); fragment2.setText("哈哈哈,我被修改了..."); Toast.makeText(getActivity(), "我是吐司", Toast.LENGTH_SHORT).show(); } }); return view; }}package com.itheima74.fragmentpassvalue;import android.app.Fragment;import android.os.Bundle;import android.support.annotation.Nullable;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;/** * Created by My on 2017/2/27. */public class Fragment2 extends Fragment { private TextView tv; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment2, null); tv = (TextView) view.findViewById(R.id.tv); return view; } /** * 暴露一个公共方法,供外部访问 * * @param content 外部传递给TextView要修改的内容 */ public void setText(String content) { tv.setText(content); }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表