Fragment与Activity 传值

一.Activity 向Fragment 传值,步骤

1.Activity 中创建Fragment 对象,调用setArguments(bundle)方法存储值

2.在fragment 中调用getArguments()获取传递的Bundle对象解析值

具体代码如下

MainActivity

package com.wgx.study.activitytofragment;

import androidx.appcompat.app.AppCompatActivity;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EdgeEffect;
import android.widget.EditText;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
    private EditText et_input;
    private Button btnClick;
    private LinearLayout contentLayout;
    private String inputContent;

    private FragmentManager manager;
    private FragmentTransaction transaction;

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

    private void initView() {
        et_input = findViewById(R.id.et_input);
        btnClick = findViewById(R.id.btnClick);
        contentLayout = findViewById(R.id.contentLayout);
    }
    private void initData() {
        manager = getFragmentManager();
        transaction = manager.beginTransaction();
        transaction.add(R.id.contentLayout, new ResultFragment());
        transaction.commit();
    }
    private void initClick() {
        btnClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendValue();
            }
        });
    }

    public void sendValue() {
        inputContent = et_input.getText().toString().trim();
        ResultFragment rf = new ResultFragment();
        Bundle bundle = new Bundle();
        bundle.putString("info", inputContent);
        rf.setArguments(bundle);
        manager = getFragmentManager();
        transaction = manager.beginTransaction();
        transaction.replace(R.id.contentLayout, rf);
        transaction.commit();
    }
}

MainActivity  layout布局文件




    

    

Fragment 

package com.wgx.study.activitytofragment;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


public class ResultFragment extends Fragment {
    private TextView tvContent;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.result_fragment, null);
        tvContent = view.findViewById(R.id.tvContent);
        Bundle bundle = getArguments();

        if (bundle != null) {
            tvContent.setText(bundle.getString("info"));
        }

        return view;
    }
}

Fragment layout布局文件




    

二、Fragment 向Activity传值步骤(回调接口)

1.在Fragment 中定义传值的回调接口,在生命周期的onAttach(或者onCreate)方法中获取接口的实现(一般直接getActivity()即可)

2.Fragment需要传值的位置调用接口回调方法传值

3.Activity实现回调接口重写回调方法获取传递的值

具体代码如下:

MainActivity
package com.wgx.study.fragmenttoactivity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

/**
 * Fragment 向Activity传值
 * 使用interface的方式
 */
public class MainActivity extends AppCompatActivity implements SendFragment.ValueListener {

    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 sendValue(String str) {
        tv_show.setText(str);
    }
}

activity 布局




    
    

fragment

package com.wgx.study.fragmenttoactivity;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


public class SendFragment extends Fragment {
    private EditText et_input;
    private Button btnClick;
    private ValueListener valueListener;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        valueListener = (ValueListener) getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.send_fragment, null);
        initView(view);
        initClick();
        return view;
    }

    private void initView(View view) {
        et_input = view.findViewById(R.id.et_input);
        btnClick = view.findViewById(R.id.btnClick);

    }
    private void initClick() {
        btnClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String info = et_input.getText().toString().trim();
                valueListener.sendValue(info);
            }
        });
    }
    public interface ValueListener{
        public void sendValue(String str);
    }
}

fragment 布局




    

    

三、Fragment 向Fragment 传值

MainActivity

package com.wgx.study.fragmenttofragment;

import androidx.appcompat.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);
    }
}

main_layout




    

    

LeftFragment

package com.wgx.study.fragmenttofragment;

import android.app.Fragment;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


public class LeftFragment extends Fragment {
    private EditText et_input;
    private Button btnClick;
    private TextView tv_show;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, null);
        initView(view);
        initClick();
        return view;
    }

    private void initView(View view) {
        et_input = view.findViewById(R.id.et_input);
        btnClick = view.findViewById(R.id.click);
        tv_show = view.findViewById(R.id.tv_show);
    }

    private void initClick() {
        btnClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String info = et_input.getText().toString().trim();
                /**
                 * 方式一
                 * 可以调用findFragmentById方法根据id获得fragment 对象,调用fragment 中的方法赋值

                 RightFragment rightFragment = (RightFragment)getFragmentManager().findFragmentById(R.id.right_fg);
                 rightFragment.setContent(info);
                 * */

                /**
                 * 方式二
                 * 先调用getFragmentManager--->findFragmentById获取Fragment对象,
                 * 然后getView 拿到另一个Fragment整体view,然后view.findviewbyid
                 * 获取需要赋值的对象
                 * */
//                TextView tvShow = getFragmentManager().findFragmentById(R.id.right_fg).getView().findViewById(R.id.tv_show);
//                tvShow.setText(info);

                /**
                 * 先调用getActivity获取所属Activity 对象,然后调用findviewbyid获取目标控件即可
                 * */
                TextView tvShow = getActivity().findViewById(R.id.tv_show);
                tvShow.setText(info);
            }
        });
    }

    public void setContent(String content) {
        if (TextUtils.isEmpty(content)) {
            return;
        }
        tv_show.setText(content);
    }
}
RightFragment
package com.wgx.study.fragmenttofragment;

import android.app.Fragment;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


public class RightFragment extends Fragment {
    private EditText et_input;
    private Button btnClick;
    private TextView tv_show;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, null);
        initView(view);
        initClick();
        return view;
    }

    private void initView(View view) {
        et_input = view.findViewById(R.id.et_input);
        btnClick = view.findViewById(R.id.click);
        tv_show = view.findViewById(R.id.tv_show);
    }
    private void initClick() {

        btnClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String info = et_input.getText().toString().trim();
//                LeftFragment leftFragment = (LeftFragment)getFragmentManager().findFragmentById(R.id.left_fg);
//                leftFragment.setContent(info);

                /**
                 * 方式二
                 * 先调用getFragmentManager--->findFragmentById获取Fragment对象,
                 * 然后getView 拿到另一个Fragment整体view,然后view.findviewbyid
                 * 获取需要赋值的对象
                 * */

//                TextView tvShow = getFragmentManager().findFragmentById(R.id.left_fg).getView().findViewById(R.id.tv_show);
//                tvShow.setText(info);

                /**
                 * 先调用getActivity获取所属Activity 对象,然后调用findviewbyid获取目标控件即可
                 * */
                TextView tvShow = getActivity().findViewById(R.id.tv_show);
                tvShow.setText(info);
            }
        });
    }

    public void setContent(String content) {
        if (TextUtils.isEmpty(content)) {
            return;
        }
        tv_show.setText(content);
    }
}

fragment 




    
    

你可能感兴趣的:(android,android-studio,interface,fragment,传值)