当前位置:网站首页>Fragment and activity value transfer

Fragment and activity value transfer

2022-06-21 17:35:00 An Xiaoniu

One .Activity towards Fragment Pass value , step

1.Activity Created in Fragment object , call setArguments(bundle) Method store value

2. stay fragment Call in getArguments() Get the delivered Bundle Object resolution value

The specific code is as follows

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 Layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/et_input"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_margin="10dp"
        android:hint=" Input content " />

    <Button
        android:id="@+id/btnClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_margin="10dp"
        android:text="click"
        android:textSize="30sp" />

    <LinearLayout
        android:id="@+id/contentLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    </LinearLayout>

</LinearLayout>

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 Layout file

<?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/tvContent"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        android:text="content"
        android:textColor="#ff0000"
        android:textSize="60sp" />
</RelativeLayout>

Two 、Fragment towards Activity Value transfer steps ( Callback interface )

1. stay Fragment The callback interface for value transfer is defined in , In the life cycle onAttach( perhaps onCreate) Method ( General direct getActivity() that will do )

2.Fragment Call the interface callback method to transfer the value at the position that needs to be transferred

3.Activity Implement the callback interface to rewrite the callback method to get the passed value

The specific code is as follows :

MainActivity
package com.wgx.study.fragmenttoactivity;

import androidx.appcompat.app.AppCompatActivity;

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

/**
 * Fragment  towards Activity Pass value 
 *  Use interface The way 
 */
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 Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:gravity="center_vertical"
        android:text="Hello World!"
        android:textSize="30sp" />
    <fragment
        android:id="@+id/sendFragment"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:name="com.wgx.study.fragmenttoactivity.SendFragment"/>

</LinearLayout>

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 Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/et_input"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_margin="10dp"
        android:hint=" Please enter the passed data " />

    <Button
        android:id="@+id/btnClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_margin="10dp"
        android:text="click"
        android:textSize="30sp" />
</LinearLayout>

3、 ... and 、Fragment towards Fragment Pass value

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/left_fg"
        android:name="com.wgx.study.fragmenttofragment.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/right_fg"
        android:name="com.wgx.study.fragmenttofragment.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:layout_weight="1" />

</LinearLayout>

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();
                /**
                 *  Mode one 
                 *  You can call findFragmentById Methods according to the id get fragment  object , call fragment  Method assignment in 

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

                /**
                 *  Mode two 
                 *  First call getFragmentManager--->findFragmentById obtain Fragment object ,
                 *  then getView  Get another one Fragment whole view, then view.findviewbyid
                 *  Get the object to be assigned 
                 * */
//                TextView tvShow = getFragmentManager().findFragmentById(R.id.right_fg).getView().findViewById(R.id.tv_show);
//                tvShow.setText(info);

                /**
                 *  First call getActivity Get belonging Activity  object , And then call findviewbyid Get the target control 
                 * */
                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);

                /**
                 *  Mode two 
                 *  First call getFragmentManager--->findFragmentById obtain Fragment object ,
                 *  then getView  Get another one Fragment whole view, then view.findviewbyid
                 *  Get the object to be assigned 
                 * */

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

                /**
                 *  First call getActivity Get belonging Activity  object , And then call findviewbyid Get the target control 
                 * */
                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 

<?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="vertical">

    <EditText
        android:id="@+id/et_input"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_margin="5dp"
        android:hint=" Please enter the passed data "
        android:textSize="30sp" />
    <Button
        android:id="@+id/click"
        android:layout_width="200dp"
        android:layout_height="60dp"
        android:layout_margin="5dp"
        android:text="click"
        android:textSize="30sp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:layout_margin="5dp"
        android:gravity="center_vertical"
        android:text=" From another fragment The data of " />

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_margin="5dp"
        android:gravity="center_vertical"
        android:text=" Display data "
        android:textColor="#ff0000"
        android:textSize="30sp" />
</LinearLayout>
原网站

版权声明
本文为[An Xiaoniu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211523011136.html