利用接口回调实现Fragment之间的跳转

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wubihang/article/details/49991821

前言

  • 在玩音乐播放器时,排行榜界面 涉及到几个Fragment之间的跳转,通过查询自己做了一个小效果,感觉不错,利用一个简单的接口回调,
    分享给初学者做着玩。大神勿喷!

这里写图片描述

  • 点击左侧的按钮,右侧的内容随着点击变化。
  • 简单介绍一下实现过程:
    • 首先界面由 左右两个Fragment构成,
    • 左侧定义了5个Button,自定义一个接口,Button监听实现接口方法,传入int类型值
    • 右侧定义一个ViewPager,在Activity中实现接口,根据Button传入的不同int,viewPager设置当前页为不同的index
    • 原理比较简单,看着挺好玩的,话不多说,直接上代码!

代码实现

  • activity_main.xml
<?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="horizontal">

    <FrameLayout
        android:id="@+id/left_view"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"/>

    <View
        android:layout_width="2dp"
        android:layout_height="match_parent"
        android:background="#9d9d9d"/>

    <FrameLayout
        android:id="@+id/right_view"
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="match_parent"/>
</LinearLayout>
  • MainActivity.class
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity implements LeftFragment.ToRightFragment{

    private FragmentManager manager;
    private FragmentTransaction transaction;

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

        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        // 替换占位布局为自定义Fragment,tag值为fragment的标示符
        transaction.replace(R.id.left_view, new LeftFragment(), "left");
        transaction.replace(R.id.right_view, new RightFragment(), "right");
        transaction.commit();
    }

    /**
     * 接口回调方法(在类的声明中实现接口)
     * @param index 实现接口方法时传的int值
     */
    @Override
    public void onToRightFragment(int index) {
        // 通过Tag,找到对应的Fragment
        RightFragment rightFragment = (RightFragment) manager.findFragmentByTag("right");
        // 通过viewPager的get方法,获得RightFragment中的viewPager
        ViewPager viewPager = rightFragment.getViewPager();

        switch (index){
            case 0:
                viewPager.setCurrentItem(0);
                break;
            case 1:
                viewPager.setCurrentItem(1);
                break;
            case 2:
                viewPager.setCurrentItem(2);
                break;
            case 3:
                viewPager.setCurrentItem(3);
                break;
            case 4:
                viewPager.setCurrentItem(4);
                break;
        }
    }
}
  • 通过接口回调,设置ViewPager的当前页码,这样点击Button,ViewPager设置对应的页码,变相的实现了类似于跳转的功能

  • LeftFragment.class

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

public class LeftFragment extends Fragment implements View.OnClickListener {

    private Button btn1, btn2, btn3, btn4, btn5;
    // 定义自定义接口
    private ToRightFragment listener;

    /**
     * 自定义接口
     */
    public interface ToRightFragment {
        // 接口中的方法,参数为int类型的值
        void onToRightFragment(int index);
    }

    /**
     * fragment与activity发生关联
     * @param context
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        // 将context转型为接口 赋值给接口对象
        listener = (ToRightFragment) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_left, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView(getView());
    }

    private void initView(View view) {
        btn1 = (Button) view.findViewById(R.id.btn_1);
        btn2 = (Button) view.findViewById(R.id.btn_2);
        btn3 = (Button) view.findViewById(R.id.btn_3);
        btn4 = (Button) view.findViewById(R.id.btn_4);
        btn5 = (Button) view.findViewById(R.id.btn_5);

        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        btn5.setOnClickListener(this);
    }

    /**
     * Button的监听事件
     * 点击Button实现接口方法,传入一个int类型的值
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_1:
                listener.onToRightFragment(0);
                break;
            case R.id.btn_2:
                listener.onToRightFragment(1);
                break;
            case R.id.btn_3:
                listener.onToRightFragment(2);
                break;
            case R.id.btn_4:
                listener.onToRightFragment(3);
                break;
            case R.id.btn_5:
                listener.onToRightFragment(4);
                break;
        }
    }

}
  • 左侧Fragment布局只有5个Button
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="国内歌手"/>

    <Button
        android:id="@+id/btn_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="欧美歌手"/>

    <Button
        android:id="@+id/btn_3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="外星歌手"/>

    <Button
        android:id="@+id/btn_4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="太阳歌手"/>

    <Button
        android:id="@+id/btn_5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="银河歌手"/>

</LinearLayout>
  • 右侧Fragment是一个ViewPager
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

public class RightFragment extends Fragment{

    private ViewPager viewPager;

    // 给viewPager一个get方法
    public ViewPager getViewPager() {
        return viewPager;
    }

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

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        viewPager = (ViewPager) getView().findViewById(R.id.view_pager);

        ArrayList<Fragment> data = new ArrayList<>();
        data.add(new InfoFragment("国内歌手"));
        data.add(new InfoFragment("欧美歌手"));
        data.add(new InfoFragment("外星歌手"));
        data.add(new InfoFragment("太阳歌手"));
        data.add(new InfoFragment("银河歌手"));

        MyAdapter adapter = new MyAdapter(getActivity().getSupportFragmentManager(), data);
        viewPager.setAdapter(adapter);

    }

    /**
     * 适配器
     */
    private class MyAdapter extends FragmentPagerAdapter {

        private ArrayList<Fragment> lists;

        public MyAdapter(FragmentManager fm, ArrayList<Fragment> lists) {
            super(fm);
            this.lists = lists;
        }

        @Override
        public Fragment getItem(int position) {
            return lists != null && lists.size() > 0 ? lists.get(position) : null;
        }

        @Override
        public int getCount() {
            return lists != null && lists.size() > 0 ? lists.size() : 0;
        }
    }
}
  • xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
  • 右侧Fragment的ViewPager显示的Fragment
package com.wu.blogdemo;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class InfoFragment extends Fragment{

    private String info;

    public InfoFragment() {
    }

    public InfoFragment(String info) {
        this.info = info;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_info, null);
        TextView tv = (TextView) v.findViewById(R.id.info_show);
        tv.setText(info);
        return v;
    }
}
  • xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/info_show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="24sp"/>
</LinearLayout>

结语

  • 如此利用接口回调,实现了Fragment之间的跳转,但是这种跳转有所限制,
    Fragment2中是一个TabLayout,在跳转到TabLayout中的FragmentX,也可以实现
    就是在实现接口时,一层一层的findFragmentByTag
    同样Fragment与Activity之间的通信也可以采用接口回调
    fragment向activity传值,通过接口回调传递给activity

猜你喜欢

转载自blog.csdn.net/wubihang/article/details/49991821