第五天 Fragment高级进阶

末鹿安然 提交于 2020-02-26 23:08:54

一、Fragment回退栈

package com.example.a04utll;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main2Activity extends AppCompatActivity {
    private Button btnTz;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        btnTz = (Button) findViewById(R.id.btn_tz);

        //管理者
        final FragmentManager fragmentManager = getSupportFragmentManager();
        //事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //对象
        BlankFragment1 blankFragment1 = new BlankFragment1();
        //添加碎片
        transaction.add(R.id.ll,blankFragment1);
        //将fragment放入回退栈中
        transaction.addToBackStack("1");
        //手动弹出栈
        fragmentManager.popBackStack();
		//提交事务
        transaction.commit();


        btnTz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Main2Activity.this, MainActivity.class);
                startActivity(intent);
            }
        });

    }
}

二、Fragment传值介绍

1.activity 给 fragment传值

主要涉及到一个方法是getArguments()和setArguments().
一个设置属性值,一个去取属性值.
步骤:
要传的值,放到bundle对象里;
在Activity中创建该Fragment的对象fragment,通过调用
fragment.setArguments()传递到fragment中;
然后更新fragment.
在该Fragment中通过调用getArguments()得到bundle对象,就能得到里面的值。

activity代码

package com.example.a05utill;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;

public class MainActivity extends AppCompatActivity {
    private EditText mEtt1;
    private Button mBtnSend;
    private FrameLayout mForever;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mEtt1 = (EditText) findViewById(R.id.ett_1);
        mBtnSend = (Button) findViewById(R.id.btn_send);
        mForever = (FrameLayout) findViewById(R.id.f1);

        final FragmentManager fragmentManager = getSupportFragmentManager();
        final FragmentTransaction transaction = fragmentManager.beginTransaction();
        BlankFragment blankFragment = new BlankFragment();
        transaction.add(R.id.f1,blankFragment);
        transaction.commit();

        mBtnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取输入的值
                String s = mEtt1.getText().toString();
                //创建fragment对象
                BlankFragment blankFragment = new BlankFragment();
                //创建bundle
                Bundle bundle = new Bundle();
                bundle.putString("name",s);
                //给fragment对象赋值
                blankFragment.setArguments(bundle);

                //修改fragment
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.add(R.id.f1,blankFragment);
                transaction.commit();
            }
        });
    }
}

fragmenty代码

package com.example.a05utill;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * A simple {@link Fragment} subclass.
 */
public class BlankFragment extends Fragment {
    private TextView mTtv;

    public BlankFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
		//获取视图
        View view = inflater.inflate(R.layout.fragment_blank, null);
        //通过视图寻找控件
        mTtv = view.findViewById(R.id.ttv);
		//获取bundle
        Bundle bundle = getArguments();
        if (bundle != null) {
            String string = bundle.getString("name");
            mTtv.setText(string);
        }
        return view;
    }

}

2.fragment 给 activity传值

1.第一种

在Activity中调用getFragmentManager()得到fragmentManager,,调用findFragmentByTag(tag)或者通过findFragmentById(id)
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(tag);

2.第二种

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

activity代码

package com.example.day004;

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

import com.example.day004.fragment.ShowTitleFragment;

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);
    }
}

fragmenty代码

package com.example.day004.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.example.day004.R;

/**
 * A simple {@link Fragment} subclass.
 */
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);
    }
}

3.fragment 给 fragment 传值(共3中)

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

package com.example.day005.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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 com.example.day005.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class LeftFragment extends Fragment {

    private EditText editText;
    private Button send_button;

    public LeftFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_left, container, false);
        editText = inflate.findViewById(R.id.left_textView_id);
        send_button = inflate.findViewById(R.id.left_button_id);

        send_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = editText.getText().toString();
                //fragment几种传值方式
                //1 
                // 通过id找的指定fragment,调用他的方法,给他的组件赋值.
                FragmentManager fragmentManager = getFragmentManager(); 
                RightFragment rightFragment=(RightFragment) fragmentManager.findFragmentById(R.id.right_fragment_id);
                rightFragment.setTextView(string);

                //2 通过id找的指定fragment,得到他所有的view.在通过findViewById 找到组件.赋值
                TextView textView = getFragmentManager().findFragmentById(R.id.right_fragment_id).getView().findViewById(R.id.right_textview_id);
                textView.setText(string);

                //3
                //因为两个fragment在一个activity里面,所有可以通过拿到activity里面所有的指定组件.
                TextView textView = (TextView) getActivity().findViewById(R.id.right_textview_id);
                textView.setText(string);

            }
        });
        return inflate;
    }
}

2.第二种

通过接口回调的方式。
与上面的接口回调用法相同

3.第三种
通过setArguments,getArguments的方式。

案例(微信底部按钮与fragment实现界面切换)

package com.example.day004.activities;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.day004.R;
import com.example.day004.fragment.FristFragment;
import com.example.day004.fragment.SecondFragment;

/**
 * 底部导航
 */
public class SelectActivity extends AppCompatActivity {
    private FrameLayout frameLayoutId;
    private RadioGroup radioGroupId;
    private RadioButton personId;
    private RadioButton messageId;
    private static final String TAG = "SelectActivity";
    private FragmentManager manager;
    private FragmentTransaction fragmentTransaction;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select);

        frameLayoutId = findViewById(R.id.frame_layout_id);
        radioGroupId = findViewById(R.id.radio_group_id);

        radioGroupId.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.person_id:
                        manager = getSupportFragmentManager();
                        fragmentTransaction = manager.beginTransaction();
//                        fragmentTransaction.replace(R.id.frame_layout_id,new FristFragment());
                        fragmentTransaction.add(R.id.frame_layout_id,new FristFragment());
                        fragmentTransaction.addToBackStack("11");
                        Log.i(TAG, "onCheckedChanged: "+SelectActivity.class.getName());
                        fragmentTransaction.commit();
                        break;
                    case R.id.message_id:
                        manager = getSupportFragmentManager();
                        manager.popBackStack();
                        SelectActivity.this.fragmentTransaction = manager.beginTransaction();
                        SelectActivity.this.fragmentTransaction.replace(R.id.frame_layout_id,new SecondFragment());
//                        fragmentTransaction.addToBackStack(null);
                        SelectActivity.this.fragmentTransaction.commit();
                        break;
                    default:
                        break;
                }
            }
        });
    }
}


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!