Fragment之间的数据互传

来源:互联网 发布:苹果mac系统更新 编辑:程序博客网 时间:2024/04/29 20:20
public class LeftFragment extends Fragment {    String[] menus = new String[]{"Android", "IOS", "WP"};    private OnClickItem onClickItem;    public LeftFragment() {        // Required empty public constructor    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        View view= inflater.inflate(R.layout.fragment_left, container, false);        ListView lv= (ListView) view.findViewById(R.id.lv_menu);        ArrayAdapter adapter=new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,menus);        lv.setAdapter(adapter);       lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {           @Override           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {//               MainActivity activity= (MainActivity) getActivity();//               activity.setContent(menus[position]);               if (onClickItem != null) {                   onClickItem.setText(menus[position]);               }           }       });        return view;    }    //自定义接口    public interface OnClickItem{        void setText(String msg);    }
public class RightFragment extends Fragment {    private TextView tv_content;    public RightFragment() {        // Required empty public constructor    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        View view=inflater.inflate(R.layout.fragment_right, container, false);        tv_content= (TextView) view.findViewById(R.id.tv_content);        return view;    }    public void set_content(String msg){        tv_content.setText(msg);    }
public class MainActivity extends AppCompatActivity implements LeftFragment.OnClickItem{    private RightFragment rfg;    private LeftFragment lfg;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        rfg= (RightFragment) getSupportFragmentManager().findFragmentById(R.id.fr_right);        lfg = (LeftFragment) getSupportFragmentManager().findFragmentById(R.id.fr_left);        //初始化LeftFragment 调用LeftFragment的set方法    }//    public void setContent(String msg){//        rfg.set_content(msg);//    }    @Override    public void setText(String msg) {        rfg.set_content(msg);    }
0 0
原创粉丝点击