Fragment进阶

本文主要介绍了Fragment回退栈及传值相关内容。在传值方面,涵盖了activity给fragment传值,通过bundle对象和特定方法实现;fragment给activity传值,有获取fragment对象和回调两种方式;fragment给fragment传值,动态和静态创建的fragment可通过不同方法获取对象并调用方法。

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

Fragment回退站

注意fragment的生命周期

public class MainActivity extends AppCompatActivity {

    private RadioButton one_radio,two_radio;
    private RadioGroup radioGroup;
    private FragmentManager manager;
    private FragmentTransaction fragmentTransaction;

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

        //初始化数据
        one_radio = findViewById(R.id.one_radio);
        two_radio = findViewById(R.id.two_radio);
        radioGroup = findViewById(R.id.radiogroup);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.one_radio:
                        manager = getSupportFragmentManager();
                        fragmentTransaction = manager.beginTransaction();
                        fragmentTransaction.add(R.id.fragment,new fristFragment());
                        //入栈
                        fragmentTransaction.addToBackStack("11");
                        fragmentTransaction.commit();
                        break;
                    case R.id.two_radio:
                        manager = getSupportFragmentManager();
                        //出栈
                        manager.popBackStack();
                        fragmentTransaction = manager.beginTransaction();
                        fragmentTransaction.replace(R.id.fragment,new secondFragment());
                        //添加了返回栈,点击back的时候,不会退出activity,而会返回到之前的fragment界面.
                        //  fragmentTransaction.addToBackStack(null);
                        fragmentTransaction.commit();
                        break;
                        default:
                            break;
                }
            }
        });
    }
}

Fragment传值

activity给fragment传值

步骤:
要传的值,放到bundle对象里;
在Activity中创建该Fragment的对象fragment,通过调用
fragment.setArguments()传递到fragment中;
然后更新fragment.
在该Fragment中通过调用getArguments()得到bundle对象,就能得到里面的值。

在这里插入图片描述
主要涉及到一个方法是getArguments()和setArguments().
一个设置属性值,一个去取属性值.

在这里插入图片描述
fragment代码

public class BlankFragment extends Fragment {

    private TextView textView;

    public BlankFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_blank, container, false);
        textView = inflate.findViewById(R.id.fm_tv_id);
        //给控件赋值
        Bundle arguments = getArguments();
        if (arguments!=null){//第一次启动一定为null,所以要判断一下
            String key = arguments.getString("key");
            textView.setText(key);
        }
        return inflate;
    }
}

activity代码

public class MainActivity extends AppCompatActivity {

    private FragmentTransaction fragmentTransaction;
    private FragmentManager fragmentManager;
    private EditText editText;

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

        editText = findViewById(R.id.editView_id);

        //动态添加fragment
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        //注意这个布局文件,是R.layout.activity_a_2_f xml文件里的线性布局
        fragmentTransaction.add(R.id.fragment_id,new BlankFragment());
        fragmentTransaction.commit();
    }

    public void onClick(View view) {
        //取到输入的值
        String string = editText.getText().toString();
        //创建fragment对象
        BlankFragment blankFragment = new BlankFragment();
        //创建bundle
        Bundle bundle = new Bundle();
        bundle.putString("key",string);
        //给fragment对象赋值
        blankFragment.setArguments(bundle);
        //动态修改fragment
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_id,blankFragment);
        fragmentTransaction.commit();
    }
}

fragment给activity传值

第一种:

在Activity中调用getFragmentManager()得到fragmentManager,,调用findFragmentByTag(tag)或者通过findFragmentById(id)

FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(tag);
第二种:

通过回调的方式,定义一个接口(可以在Fragment类中定义),接口中有一个空的方法,在fragment中需要的时候调用接口的方法,值可以作为参数放在这个方法中,然后让Activity实现这个接口,必然会重写这个方法,这样值就传到了Activity中.
大白话,就是java的父类引用指向了子类对象
Activity中的代码

public class F2AActivity extends AppCompatActivity implements ShowTitleFragment.MyListener {

    private TextView textView;
    @Override
    public void sendMessage(String string) {
        textView.setText(string);
    }

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

Activity中的xml文件

<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:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".F2AActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/f2a_tv_id"
        android:textSize="30sp"
        android:hint="提示而已"
        />

    <fragment
        android:name="com.example.day004.fragment.ShowTitleFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/f2a_fm_id">

    </fragment>

fragment中的代码

public class ShowTitleFragment extends Fragment {

    private EditText editText;
    private Button button;

    private MyListener listener;

    public ShowTitleFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //拿到与当前fragment关联的Activity.
        listener = (MyListener) getActivity(); 
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_show_title, container, false);

       //取到所有控件
        editText = inflate.findViewById(R.id.fm_title_et_id);
        button = inflate.findViewById(R.id.fm_title_button_id);
        //点击事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = editText.getText().toString();
                if(string != null){
                    //注意了.这里是父类引用指向了子类对象,其实是activity中的sendmessage方法在执行.
                    listener.sendMessage(string);
                }
            }
        });
		//返回fragment中的布局视图
        return inflate;
    }

   //自定义的接口
    public interface MyListener{
        void sendMessage(String string);
    }

}

fragment中的xml文件

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/fm_title_et_id"
    android:hint="整的啥吧"
    />

<Button
    android:id="@+id/fm_title_button_id"
    android:text="发送了啊"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
在这里插入代码片

fragment给fragment传值

第一种:
动态创建的fragment通过findFragmentByTag得到另一个的Fragment的对象,这样就可以调用另一个的方法了。
左边布局

在这里插入图片描述
右边布局

在这里插入图片描述
左边fragment代码

public class FirstFragment extends Fragment {

    private EditText first_et;
    private Button first_bt;

    public FirstFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_first, container, false);
        first_et = inflate.findViewById(R.id.first_ed_id);
        first_bt = inflate.findViewById(R.id.first_bt_id);

        first_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = first_et.getText().toString();
                TextView textView = getActivity().findViewById(R.id.second_tv_id);
                textView.setText(string);
            }
        });

        return inflate;
    }
}

右边fragment代码

public class SecondFragment extends Fragment {

    private TextView textView;

    public SecondFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_second, container, false);
        textView = inflate.findViewById(R.id.second_tv_id);

        return inflate;
    }
}

activity布局
在这里插入图片描述
activity代码

public class MainActivity extends AppCompatActivity {

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

静态创建的fragment通过findFragmentById得到另一个的Fragment的对象,这样就可以调用另一个的方法了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值