Activity和Fragment交互

本文介绍了Activity如何访问Fragment中的控件和成员变量,Fragment访问Activity的机制,以及多个Fragment之间的通信方式,详细阐述了不同场景下的交互实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Activity和Fragment的交互有三种:
1.Activity访问Fragment中的控件、成员变量
2.Fragment访问Activity中的控件、成员变量
3.多个Fragment之间通讯

1.Activity访问Fragment中的控件、成员变量

这里写图片描述

如图:
   Activity中有一个CheckBox,底部是一个Fragment包含一个TextView和一个Button,点击CheckBox的时候得到Activity中成员变量的名字改变Fragment中TextView的值,点击Fragment中Button的时候得到CheckBox的状态显示Toast。
Fragment的xml布局:
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/tv_status"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center" />

    <Button
        android:id="@+id/bt_status"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="@string/get_status"
        android:textSize="13sp" />

</LinearLayout>

Fragment中onCreateView()方法中返回一个View:

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
     View view = inflater.inflate(R.layout.fragment_bottom,container,false);
    bt_getStatus = (Button)                  view.findViewById(R.id.bt_status);
    return view;
 }

Activity的xml布局

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<CheckBox
    android:id="@+id/cb"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:text="@string/isMarry" />

<fragment
    android:id="@+id/bottomFragment"
    android:name="com.example.fragment_less03.fragment.BottomFragment"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="40dp" />


Activity中,CheckBox设置状态改变监听方法中实现访问Fragment的代码:

 cb_isMarry.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {

    //通过id或者tag获取Fragment
    BottomFragment fragment = (BottomFragment)getFragmentManager().findFragmentById(R.id.bottomFragment);
    if (fragment != null) {
       //访问Fragment的成员变量
        fragment.setPersonName("LingDang");
        //getView()获取View
        TextView tv_status = (TextView) fragment.getView()
                           .findViewById(R.id.tv_status);
        if (isChecked) {                        、                   tv_status.setText(fragment.getPersonName()+"已婚");
                    } else {                        tv_status.setText(fragment.getPersonName()+"未婚");
                    }
                }
            }
        });
   通过getFragmentManager().findFragmentById(R.id.bottomFragment);或者getFragmentManager().findFragmentByTag(String str);可以得到Fragment,Fragment对象再根据getView()返回一个View。根据返回的Fragment对象和View对象,即可访问Fragment的成员变量和控件

2. Fragment访问Activity:

代码还是的,在Fragment中添加代码:
//
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
    bt_getStatus.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        CheckBox cb_isMarry = (CheckBox) getActivity().findViewById(R.id.cb);
        boolean isCheck = cb_isMarry.isChecked();
        if (isCheck) {
            Toast.makeText(getActivity(), "已选中", 1000).show();
        }else{
            Toast.makeText(getActivity(), "未选中", 1000).show();
        }
    }
    });
        super.onActivityCreated(savedInstanceState);
}
    在onActivityCreated()方法中保证Activity的onCreate()方法调用完成。必须有super.onActivityCreated(savedInstanceState)才正确。
    通过getActivity()可以得到Fragment对应的Activity,即可访问Activity中的内容。但是这样Fragment就和特定的Activity关联起来了,不利于Fragment的复用。我们可以这么做:
    1.在Fragment中创建一个接口,并创建一个接口实例
    2.在Fragment的onAttach中要求Activity实现该接口,点击的时候接口实例调用相应的方法
    3.Activity实现Fragment对应的接口,实现方法
    具体的请看多个Fragment通信

3.多个Fragment通信

 效果图:

这里写图片描述

   上边是InputFragment,只有一个EditText,下边是继承自ListFragment的ShowFragment。InputFragment输入一个字符串后点击回车在ShowFragment新增InputFragment输入的字符串,InputFragment的EditText的text设置为空。

   多个Fragment通信的具体步骤:
   1.在Fragment中创建一个接口,并创建一个接口实例
   2.在Fragment的onAttach中要求Activity实现该接口,点击的时候接口实例调用相应的方法
   3.Activity实现Fragment对应的接口,实现方法

   代码:
   InputFragment的xml
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/edit"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:hint="input something"
    android:singleLine="true" >
 </EditText>
InputFragment代码:
 public class InputFragment extends Fragment {

    private View view;
    EditText edit;

    public interface OnNewItemAddListener{
        public void newItemAdd(String str);
    }

    private OnNewItemAddListener listener;

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        //要求Fragment所附着的Activity必须实现这个方法
        try{
            listener = (OnNewItemAddListener)activity;
        }catch(Exception e){
            throw new ClassCastException(activity.toString()+"must implement OnNewItemAddListener");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        view = inflater.inflate(R.layout.fragment_input, null);
        edit = (EditText) view.findViewById(R.id.edit);
        edit.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_ENTER) {                                    listener.newItemAdd(edit.getText().toString());
                        edit.setText("");
                        return true;
                    }
                }
                return false;
            }
        });
        return view;
    }
} 
edit.setText("");前面还有一句listener.newItemAdd(edit.getText().toString());
ShowFragment代码:

 public class ShowFragment extends ListFragment {
    @Override
    public View onCreateView(LayoutInflater inflater,                  ViewGroup container,Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return super.onCreateView(inflater, container,        savedInstanceState);
}

}

Activity的xml布局

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >


<fragment 
    android:id="@+id/input"       android:name="com.example.twofragment.fragment.InputFragment"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    />

  <fragment 
    android:id="@+id/show"
    android:name="com.example.twofragment.fragment.ShowFragment"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

Activity代码:

     public class MainActivity extends Activity implements OnNewItemAddListener{

    private ArrayList<String> datas = new ArrayList<String>();
    private ArrayAdapter adapter;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, datas);
        ShowFragment fragment = (ShowFragment) getFragmentManager().findFragmentById(R.id.show);
        fragment.setListAdapter(adapter);
    }

    @Override
    public void newItemAdd(String str) {
        datas.add(str);
        adapter.notifyDataSetChanged();
    }

}
按照上面的步骤编写即可,代码挺简单的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值