iT邦幫忙

0

Android studio 實現選項卡功能

  • 分享至 

  • xImage
  •  

實現所需要的class跟xml
1.本身的activity 配戴著xml
2.需要幾個選項 就new 幾個Fragement 每個Fragement都會配戴一個xml
3.new 一個java類別 取名叫FragmentAdapter 並繼承extends FragmentStateAdapter

先附上本身的activity碼

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;

public class MainActivity1_2 extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager2 viewPager2;
    FragmentAdapter fragmentAdapter;

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

        tabLayout = findViewById(R.id.tab_layout);
        viewPager2 = findViewById(R.id.view_pager2);

        FragmentManager fm = getSupportFragmentManager();

        fragmentAdapter = new FragmentAdapter(fm,getLifecycle());
        //getLifecycle()是獲取生命週期

        viewPager2.setAdapter(fragmentAdapter);
        //viewPager2 設定調配器 是 fragment調配器也是一個class 要帶參數的class

        tabLayout.addTab(tabLayout.newTab().setText("First"));
        tabLayout.addTab(tabLayout.newTab().setText("two"));
        tabLayout.addTab(tabLayout.newTab().setText("three"));
        //tabLayout 增加三個按鈕 並顯示名字

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager2.setCurrentItem(tab.getPosition());

            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

            viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                @Override
                public void onPageSelected(int position) {
                    tabLayout.selectTab(tabLayout.getTabAt(position));
                }
            });

    }

}

跟activity的xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity1_2">


<com.google.android.material.tabs.TabLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tab_layout"/>

    <androidx.viewpager2.widget.ViewPager2
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tab_layout"
        android:id="@+id/view_pager2"/>
    
    </RelativeLayout>

new 出來的Fragement 本身class 是不用修改的
但還是附上 其他的Fragement也是一樣 所以我只貼上一個

package com.example.myapplication;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FirstFragement#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class FirstFragement extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FirstFragement.
     */
    // TODO: Rename and change types and number of parameters
    public static FirstFragement newInstance(String param1, String param2) {
        FirstFragement fragment = new FirstFragement();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }
}

Fragement的xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FirstFragement">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="第一個頁面"
        android:gravity="center"

        />
</FrameLayout>

最後的FragmentAdapter code 這邊return
是我Fragment名稱 共三個分別為
new FirstFragement();
new SecondFragment();
new ThirdFragment();
你有幾個選項//Fragment 就需要在這邊設定 跟case

package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;

public class FragmentAdapter extends FragmentStateAdapter {

    public FragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull  Lifecycle lifecycle) {
        super(fragmentManager, lifecycle);
    }
    //建構式的參數是片段經理 跟 生命週期

    @NonNull
    @Override
    public Fragment createFragment(int position) {

        switch (position){
            case 1 :
                return new SecondFragment();
            case 2:
                return new ThirdFragment();
        }

        return new FirstFragement();
    }

    @Override
    public int getItemCount() {
        return 3;
    }
}


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
youxiang8727
iT邦新手 4 級 ‧ 2021-12-04 23:22:28

不好意思請問一下,我查到的資料是寫說androidx.Fragment現在沒有getSupportFragmentManager()這個方法,有其他的替代方案嗎

阿沒事了 我把activity extend從appcompatactivity換成fragmentactivity就可以用了

我要留言

立即登入留言