Fragment与Activity间的通信 Fragment与Fragment间的通信

Fragment与Activity间的通信

视频Fragment与Acctivity间的通信

Activity向Fragment传值

Activity向引入的Fragment传值步骤:
1.Activity中创建Fragment对象,调用setArguments(bundle)方法储存值
2.Fragment中调用getArguments()获取传递的bundle对象解析获取具体值

示例代码

MainActivity.java

package com.example.activitytofragment;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText et_content;
    private FragmentManager manager;
    private FragmentTransaction transaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_content = findViewById(R.id.et_content);
        manager = getFragmentManager();
        transaction = manager.beginTransaction();
        transaction.add(R.id.ll_content,new ResultFragment());
        transaction.commit();
    }

    /**
     * 点击按钮将EditText中输入的文本传入ResultFragment中
     */
    public void sendValue(View view){
        // 获取输入的文本信息
        String info = et_content.getText().toString().trim();
        ResultFragment fragment = new ResultFragment();
        // 创建Bundle对象,把需要传递的数据存到bundle里,然后调用fragment的setArguments()方法传递bundle
        Bundle bundle = new Bundle();
        bundle.putString("to",info);
        fragment.setArguments(bundle);
        // 开启事务
        transaction = manager.beginTransaction();
        // 替换之前没有数据的Fragment
        transaction.replace(R.id.ll_content,fragment);
        // 提交事务
        transaction.commit();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.example.activitytofragment.MainActivity">

    <EditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/et_content" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击传值"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:layout_below="@id/et_content"
        android:onClick="sendValue"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_below="@id/btn"
        android:id="@+id/ll_content">

    </LinearLayout>


</RelativeLayout>

ResultFragment.java

package com.example.activitytofragment;

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;


public class ResultFragment extends Fragment {

    private TextView tv_content;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_layout, null);
        tv_content = view.findViewById(R.id.tv_content);
        // 先调用getArguments()方法获取bundle  bundle对象中根据key获取传递的数据,再展示到TextView中
        Bundle bundle = getArguments();
        if (bundle != null) {
            String info = bundle.getString("to");
            tv_content.setText(info);
        }
        return view;
    }
}

fragment_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_content"
        android:textSize="30sp"
        android:gravity="center"/>
</android.support.constraint.ConstraintLayout>

效果图

这里写图片描述

Fragment向Activity传值

Fragment向所在Activity传值步骤:
1.Fragment中定义传值的回调接口,在生命周期onAttach()或者onCreate()方法中获取接口的实现
2.Fragment需要传值的位置调用接口回调方法传值
3.Activity实现回调接口重写回调方法获取传递的值
代码示例:
MainActivity.java

package com.example.fragmenttoactivity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements ResourceFragment.MyListener{

    private TextView tv_show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_show = findViewById(R.id.tv_show);
    }

    @Override
    public void sendMessage(String str) {
        // 判断不等于空也不等于双引号空格
        if (str!=null&&!"".equals(str)){
            // 回传数据进行展示
            tv_show.setText(str);
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.example.fragmenttoactivity.MainActivity">

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp" />

    <fragment
        android:id="@+id/fragment_resource"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tv_show"
        android:name="com.example.fragmenttoactivity.ResourceFragment"/>

</RelativeLayout>

ResourceFragment.java

package com.example.fragmenttoactivity;

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.Button;
import android.widget.EditText;


public class ResourceFragment extends Fragment {

    private EditText et_content;
    private Button button;
    private MyListener listener;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 实例话MyListener,因为Activity实现了MyListener,所以就是他的子类
        listener = (MyListener) getActivity();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_resource,null);
        et_content = view.findViewById(R.id.et_content);
        button = view.findViewById(R.id.btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取EditText中的值
                String info = et_content.getText().toString().trim();
                // 接口回传的形式回传数据
                listener.sendMessage(info);
            }
        });
        return view;
    }

    // 定义接口 接口中定义回传数据的方法
    public interface MyListener{
        public abstract void sendMessage(String str);
    }
}

fragment_resource.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/et_content" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_content"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:text="@string/btn" />

</RelativeLayout>

效果图
这里写图片描述

同一个Activity下的Fragment与Fragment之间的传值

同一个Activity中不同Fragment之间的传值有三种方法:
方法一:先得到FragmentManager,再调用findFragmentById()方法,根据id获取到Fragment对象,调用fragment中的setTextView()方法赋值
方式二:先调用getFragmentManager()获得FragmentManager对象,然后调用findFragmentById()方法获得右侧的Fragment对象,再调用getView()获得右侧的fragment的view对象,最后调用view的findViewById()方法获得需要赋值的控件
方式三:先调用getActivity()获取所属Activity的对象,再通过activity的findViewById()获取目标控件
代码示例
MainActivity.java

package com.example.fragmenttofragment;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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="horizontal"
    tools:context="com.example.fragmenttofragment.MainActivity">

    <fragment
        android:id="@+id/fragment_left"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:name="com.example.fragmenttofragment.LeftFragment"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/fragment_right"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:name="com.example.fragmenttofragment.RightFragment"
        android:layout_weight="1" />
</LinearLayout>

LeftFragment.java

package com.example.fragmenttofragment;

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.Button;
import android.widget.EditText;
import android.widget.TextView;


public class LeftFragment extends Fragment {

    private EditText et_content;
    private Button btn_send;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_left,null);
        et_content = view.findViewById(R.id.et_content);
        btn_send = view.findViewById(R.id.btn_send);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String info = et_content.getText().toString().trim();   // 获取输入的内容
/*                // 方式一:先得到FragmentManager,再调用findFragmentById()方法,根据id获取到Fragment对象,调用fragment中的setTextView()方法赋值
                RightFragment rightFragmenet = (RightFragment) getFragmentManager().findFragmentById(R.id.fragment_right);
                rightFragmenet.setTextView(info);*/

/*                // 方式二:先调用getFragmentManager()获得FragmentManager对象,然后调用findFragmentById()方法获得右侧的Fragment对象,
                //         再调用getView()获得右侧的fragment的view对象,最后调用view的findViewById()方法获得需要赋值的控件
                TextView tv_show = getFragmentManager().findFragmentById(R.id.fragment_right)
                        .getView().findViewById(R.id.tv_show);
                tv_show.setText(info);*/

                // 方式三:先调用getActivity()获取所属Activity的对象,再通过activity的findViewById()获取目标控件
                TextView tv_show = getActivity().findViewById(R.id.tv_show);
                tv_show.setText(info);

            }
        });
        return view;
    }
}

fragment_left.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:hint="@string/et_content" />

    <Button
        android:id="@+id/btn_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/et_content"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:text="@string/btn_send" />

</RelativeLayout>

RightFragment.java

package com.example.fragmenttofragment;

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;

public class RightFragment extends Fragment {

    private TextView tv_show;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_right,null);
        tv_show = view.findViewById(R.id.tv_show);
        return view;
    }

    // 定义一个方法给TextView赋值
    public void setTextView(String text){
        tv_show.setText(text);
    }
}

fragment_right.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="30sp" />

</RelativeLayout>

效果图
这里写图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章