1. 程式人生 > >利用介面回撥實現Fragment之間的跳轉

利用介面回撥實現Fragment之間的跳轉

前言

  • 在玩音樂播放器時,排行榜介面 涉及到幾個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

相關推薦

利用介面實現Fragment之間

前言 在玩音樂播放器時,排行榜介面 涉及到幾個Fragment之間的跳轉,通過查詢自己做了一個小效果,感覺不錯,利用一個簡單的介面回撥, 分享給初學者做著玩。大神勿噴! 點選左側的按鈕,右側的內容隨著點選變化。 簡單介紹一下實現過程: 首先介面

Android 介面實現Fragment

---------------------MainActivity------------------- package com.example.earl.fragmentinterfacejump; import android.app.Activity; import androi

Activity與Fragment之間實現

1.實現Activity到Fragment之間的跳轉 首先在MainActivity的條件函式中加入如下程式碼 Intent mIntent = new Intent(MainActivity.this,Menu.class); mIntent.putExtra("id",1); start

組合自定義控制元件,介面實現T

效果圖: 1.自定義佈局 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"

介面實現RecyclerView的條目點選事件

1.介面卡中新增如下程式碼 public interface OnItemClickListener { public void onItemClick(int postion); } OnItemClickListener mClickListener; pu

介面fragment中的使用

         我們知道在兩個fragment之間傳遞資料要通過activity,如果兩個fragment之間發生了資料的傳遞,如果這時我們的螢幕發生翻轉activity將會啟動onCreate()方法,這時fragment中的狀態和資料將會被重置而得不到儲存,那麼如果我

關於在Fragment中通過Activity介面操作Fragment中控制元件報空指標問題

現象描述:當Activity中某個變數改變時候,需要通知到Fragment我們常常用介面實現...。。我們在Activity中先replace,commit該Fragment,接著呼叫介面需要改變變數的方法。。。然後我們在Fragment中的介面回撥方法裡,更具該變數操縱F

Intent實現頁面之間

(首發於 2017 年 9 月 14 日) 1. Intent實現頁面之間的跳轉 1.1 無資料傳遞頁面跳轉 1 Intent intent = new Intent(MainActivity.this,DemoActivity.class); 2 startActivity(intent);

利用jquery&iframe標籤實現頁面無的表單檔案上傳

最近公司專案修改上傳檔案效果,大致效果就是上傳檔案提交時不能進行頁面跳轉,然後最好是沒有提交按鈕,用jquery實現表單的提交。想了想,用ajax好像不太好實現這種效果了,首先是ajax如何把上傳的檔案傳遞給後臺就遇到了瓶頸;其次再是如何配合ajax實現jque

使用帶參建構函式 實現窗體之間傳值

使用帶參建構函式  //test1程式碼 private void btntest_Click(object sen

Fragment學習之使用介面的方式實現Fragment與Activity通訊

Fragment與Fragment之間可以進行資訊傳遞,同樣,Fragment與Activity也可以進行資訊的傳遞。 下面是一個演示在Activity中獲取來自Fragment的資訊,使用介面回撥的方法在Activity中接收資訊 MainActivity.java:

AIDL實現不同應用之間跨程序通訊及傳遞與返回各種資料型別和遠端介面

含義:AIDL(Android Interface Definition Language),是android介面定義語言,這種語言定義了一個客戶端和伺服器通訊介面的一個標準、規範。 為什麼要有AIDL?  我們都知道android中的四大元件Activit

Fragment(3)和其他Fragment之間互動--偉大的介面

這個是我一直想要找的,沒想到偉大的官網竟然有。感動到流鼻涕了。。 為了重用Fragment UI元件,我們應該建立一個完全獨立的自控的,定義自己佈局和行為的模型元件。一旦我們定義了這些可重用的Fragments,我們就可以把它們和Activity關聯起來並且用應用邏輯連線

Fragment之間的傳值 介面

//佈局 <fragment android:id="@+id/frag_left" android:name="baidumaplocation.bawei.com.chuanzhirecycle.Fragment1" android:layout_width=

基於介面詳解JUC中Callable和FutureTask實現原理

Callable介面和FutureTask實現類,是JUC(Java Util Concurrent)包中很重要的兩個技術實現,它們使獲取多執行緒執行結果成為可能。它們底層的實現,就是基於介面回撥技術。介面回撥,許多程式設計師都耳熟能詳,這種技術被廣泛應用於非同步模組的開發中。它的實現原理並不複雜,但是對初學

Activity與Fragment通過介面進行通訊

介面回撥在Android中有很多的應用,比如Activity裡的onCreat、onDestroy等方法,按鍵事件監聽。Android對Fragment的是在Android3.0時加入的,所以Android3.0  以前的系統並不支援Fragment,而為了使3.0以前的

Android通過介面實現資料更新(Kotlin版)

最近開發一個專案,用的是kotlin,本人kotlin水平有限,還請諒解,需要在fragment修改資料,然後更新到activity中,我使用介面回撥來完成這個需求。 先上一張圖來看一下 修改完暱稱,不僅要在fragment裡更新資料,還要同步更新act

C#實現介面

通常情況下,我們建立一個物件,並馬上直接去使用它的方法。然而,在有些情況下,希望能在某個場景出現後或條件滿足時才呼叫此物件的方法。回撥就可以解決這個“延遲呼叫物件方法”的問題。這個被呼叫方法的物件稱為回撥物件。 實現回撥的原理簡介如下: 首先建立一個回撥

kotlin 多介面實現方式(一)

沒啥好說的,看標題就明白了。程式碼比較繞,慢慢看…. 本來想解釋下程式碼,不過可能還在受上一篇帖子的影響吧,不知道說些什麼… 有不明白的留言吧… 可以先把程式碼複製一份到電腦上執行一下,先看看效果 package com.example.kotlin

兩個Activity之間介面進行通訊

因為剛接觸的一個專案是藍芽連線,需求是要在掃描介面點選條目進行連線 時,在跳轉的另一個activity(姑且先叫它連線介面吧)上顯示連線的過程, 也就是彈出一個dialog,所以就需要用介面回撥