iT邦幫忙

0

androidx fragment 筆記

  • 分享至 

  • xImage
  •  

參考:https://blog.csdn.net/harvic880925/article/details/44917955
生命時程

https://stackoverflow.com/questions/16036572/how-to-pass-values-between-fragments
https://blog.csdn.net/harvic880925/article/details/44131865

public static Fragment2 newInstance(String text) {
Fragment2 fragment = new Fragment2();
Bundle args = new Bundle();
args.putString("param", text);
fragment.setArguments(args);
return fragment;
String strtext=getArguments().getString("message");

commit 是一次提交為單位的 所以如果你add A + add BC pop也會是 pop BC + pop A
每添加一次就要用addToBackStack
manager.popBackStack("fragment2",0);//通過TAG回推 0是在當前頁面
manager.popBackStack("fragment2",FragmentManager.POP_BACK_STACK_INCLUSIVE);

用FragmentManager+ fragmentTransaction共同管理~~~
//還原到第一頁

1.先在gradle加這段
implementation 'com.google.android.material:material:1.0.0-rc01'
2.創建你的fragment new>add>fragment

  public class HomeFragment extends Fragment {

    private TextView mTextTitle;

    public HomeFragment() {
        // Requires empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
         View root = inflater.inflate(R.layout.fragment_home, container, false);
                              //ur layout ,container,false>不會自動創建layout (boolean atatch root) true的話會除了fragment外的都刪掉
        mTextTitle = (TextView) root.findViewById(R.id.text_title_home);
        return root;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTextTitle.setText("Fire in the home(x) hole(o)!");
                mTextTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity) getActivity()).onOpenDetail("Open from Dashboard!");
                //接資料
            }
        });
    }
}
mainactivity.java
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFragmentManager = getFragmentManager();
        //管理fragment
        ((BottomNavigationView) findViewById(R.id.navigation)).setOnNavigationItemSelectedListener(this);
        ((BottomNavigationView) findViewById(R.id.navigation)).setSelectedItemId(R.id.navigation_home);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        //可以用來add(在線頂最上層) remove replace(全部拿出來再放入)
        //add 跟 replace 會對沖 不能同時用
        if (mFragmentManager.findFragmentByTag(DETAIL) != null) {
            mFragmentManager.popBackStack();//從線頂拿出來
        }

        switch (item.getItemId()) {
            case R.id.navigation_home:

                if (mHomeFragment == null) mHomeFragment = new HomeFragment();
                if (mDashboardFragment != null) fragmentTransaction.hide(mDashboardFragment);
//                if (mNotificationsFragment != null) fragmentTransaction.hide(mNotificationsFragment);
                if (mHomeFragment.isAdded()) {
                    fragmentTransaction.show(mHomeFragment);
                } else {
                    fragmentTransaction.add(R.id.container_main, mHomeFragment, HOME);
                    /*add(int containerViewId, Fragment fragment, String tag);*/
                }
                fragmentTransaction.commit();//一次性繳交

                return true;
            case R.id.navigation_dashboard:
                if (mDashboardFragment == null) mDashboardFragment = new DashboardFragment();
                if (mHomeFragment != null) fragmentTransaction.hide(mHomeFragment);
            //    if (mNotificationsFragment != null) fragmentTransaction.hide(mNotificationsFragment);
                if (mDashboardFragment.isAdded()) {
                    fragmentTransaction.show(mDashboardFragment);
                } else {
                    fragmentTransaction.add(R.id.container_main, mDashboardFragment, DASHBOARD);
                }
                fragmentTransaction.commit();

                return true;
            case R.id.navigation_notifications:

//                if (mNotificationsFragment == null) mNotificationsFragment = new NotificationFragment();
//                if (mHomeFragment != null) fragmentTransaction.hide(mHomeFragment);
//                if (mDashboardFragment != null) fragmentTransaction.hide(mDashboardFragment);
//                if (mNotificationsFragment.isAdded()) {
//                    fragmentTransaction.show(mNotificationsFragment);
//                } else {
//                    fragmentTransaction.add(R.id.container_main, mNotificationsFragment, NOTIFICATIONS);
//                }
//                fragmentTransaction.commit();
//
//                return true;
        }
        return false;
    }

    public void onOpenDetail(String message) {

        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
         // 如果目前顯示的頁面是 home fragment
        if (mHomeFragment != null && !mHomeFragment.isHidden()) {
            fragmentTransaction.hide(mHomeFragment);
            fragmentTransaction.addToBackStack(HOME);
            //transaction.addToBackStack(String tag);
        }
        if (mDashboardFragment != null && !mDashboardFragment.isHidden()) {
            fragmentTransaction.hide(mDashboardFragment).addToBackStack(DASHBOARD);
        }
//        if (mNotificationsFragment != null && !mNotificationsFragment.isHidden()) {
//            fragmentTransaction.hide(mNotificationsFragment).addToBackStack(NOTIFICATIONS);
//        }

        DetailFragment fragment = new DetailFragment();
        Bundle bundle = new Bundle();
        bundle.putString(DETAIL_MESSAGE, message);
        fragment.setArguments(bundle);

        fragmentTransaction.add(R.id.container_main, fragment, DETAIL).commit();

    }
//main.xml
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_height="match_parent"
tools:context=".MainActivity">

<FrameLayout
    android:id="@+id/container_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="50dp" >

</FrameLayout>

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="0dp"
    android:layout_marginStart="0dp"
    android:background="?android:attr/windowBackground"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:menu="@menu/navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

menu資料夾內 
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="title_home" />

    <item
        android:id="@+id/navigation_dashboard"
        android:icon="@drawable/ic_dashboard_black_24dp"
        android:title="title_dashboard" />

    <item
        android:id="@+id/navigation_notifications"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="title_notifications" />
</menu>


**第二種**

用tablayout + viewpager
main.xml
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:layout_height="match_parent"
    tools:context=".Two"
    >

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#f00"
        android:layout_gravity="bottom">

            <com.google.android.material.tabs.TabLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="top"
                android:id="@+id/tabs">
                <com.google.android.material.tabs.TabItem
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:text="red">

                </com.google.android.material.tabs.TabItem>
                <com.google.android.material.tabs.TabItem
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:text="green">

                </com.google.android.material.tabs.TabItem>
                <com.google.android.material.tabs.TabItem
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:text="blue">

                </com.google.android.material.tabs.TabItem>
            </com.google.android.material.tabs.TabLayout>

    </com.google.android.material.appbar.AppBarLayout>
    <androidx.viewpager.widget.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/viewpager">
    </androidx.viewpager.widget.ViewPager>



</androidx.coordinatorlayout.widget.CoordinatorLayout>
mainactivity.java

public class Two extends AppCompatActivity {
    public PreferencesHelperImp preferencesHelperImp;
    TabLayout tabLayout;
    ViewPager viewPager;
    PageAdapter pageAdapter;
    Toolbar toolbar,toolbartab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
      //  TextView textView=(TextView) findViewById(R.id.text);
//        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("sharedPreferences", MODE_PRIVATE);
//        String email=sharedPreferences.getString("data","");
       // TextView textView = (TextView)findViewById(R.id.email);
//        textView.setText(email);
        preferencesHelperImp = new PreferencesHelperImp(getApplicationContext());
        String email = preferencesHelperImp.getStringData();

        Log.d("Mainactivity", "onClick: " + email);
        tabLayout=(TabLayout)findViewById(R.id.tabs);
        viewPager=(ViewPager)findViewById(R.id.viewpager);
//        toolbar=(Toolbar)findViewById(R.id.toolbar);
//        toolbartab=(Toolbar)findViewById(R.id.toolbartab);
        //setSupportActionBar(toolbar);

        pageAdapter=new PageAdapter(getSupportFragmentManager());
        pageAdapter.addFragment(new RedFragment(),"Red");
        pageAdapter.addFragment(new GreenFragment(),"Green");
        pageAdapter.addFragment(new BlueFragment(),"Blue");

        viewPager.setAdapter(pageAdapter);
        viewPager.setPageTransformer(true,new DepthPageTransformer());
        //轉場方式
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()){
                    case 0:
                        getWindow().setStatusBarColor(RED);
                        tabLayout.setBackgroundColor(RED);
                        break;
                    case 1:
                        getWindow().setStatusBarColor(GREEN);
                        tabLayout.setBackgroundColor(GREEN);
                        break;
                    case 2:
                        getWindow().setStatusBarColor(BLUE);
                        tabLayout.setBackgroundColor(BLUE);
                        tabLayout.setTabTextColors(ColorStateList.valueOf(WHITE));
                        break;
                }
            }

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

            }

            @Override

            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

}

//pageadapter
public class PageAdapter extends FragmentPagerAdapter {
    ArrayList<Fragment> fragmentArrayList;
    ArrayList<String> fragmentTitle;
    PageAdapter(FragmentManager fmng){
        super(fmng);;
        fragmentArrayList=new ArrayList<>();
        fragmentTitle=new ArrayList<>();
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return fragmentArrayList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentArrayList.size();
    }
    public  void  addFragment(Fragment fragment,String title){
        fragmentArrayList.add(fragment);
        fragmentTitle.add(title);
    }
    //----------androidx whilte tabs text not in 9+

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentTitle.get(position);
    }
}
redfragment
public class RedFragment 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;

    private OnFragmentInteractionListener mListener;

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

    /**
     * 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 RedFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RedFragment newInstance(String param1, String param2) {
        RedFragment fragment = new RedFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @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
        View r=inflater.inflate(R.layout.fragment_red2, container, false);

        setHasOptionsMenu(true);
        return r ;
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_red,menu);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

//    @Override
//    public void onAttach(Context context) {
//        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
//    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

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

尚未有邦友留言

立即登入留言