add an actionbar for each fragment

吃可爱长大的小学妹 提交于 2020-04-16 02:41:25

问题


Suppose I have 4 fragments that I put in mainActivity, I want to create different actionbar different in each frgament.

When I press fragment 1 then the actionBar appears fragment 1, when I press the two fragment that appears actoinbar belonging to fragment 2

01-02 20:12:33.700 15035-15035/src.go_letskerja E/AndroidRuntime: FATAL EXCEPTION: main
                                                              Process: src.go_letskerja, PID: 15035
                                                              java.lang.NullPointerException
                                                                  at src.go_letskerja.Fragment.OtherFragment.onCreateView(OtherFragment.java:26)
                                                                  at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
                                                                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
                                                                  at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                  at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
                                                                  at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
                                                                  at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
                                                                  at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
                                                                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
                                                                  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
                                                                  at android.os.Handler.handleCallback(Handler.java:733)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                  at android.os.Looper.loop(Looper.java:136)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:5113)
                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                  at java.lang.reflect.Method.invoke(Method.java:515)
                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
                                                                  at dalvik.system.NativeStart.main(Native Method)

This my Activity :

    package src.go_letskerja.Fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import src.go_letskerja.R;


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


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

        ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("TES");
        //((AppCompatActivity)getActivity()).getSupportActionBar().setCustomView(R.layout.actionbar);

        return v;
    }
}

This my XML :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:fitsSystemWindows="true"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="10dp"
        android:paddingTop="10dp"
        android:text="Tinggi Badan"
        android:textSize="14dp" />

    <TextView
        android:id="@+id/tinggibadan"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="15dp"
        android:paddingLeft="30dp"
        android:paddingTop="10dp"
        android:text="000 Cm"
        android:textSize="20dp"
        android:textStyle="bold" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/list" />


</LinearLayout>

回答1:


Yes, you can add the custom toolbar to your fragment and make your activity theme with no action bar in the Manifest and do something like this. this layout may be your fragment layout and inflate in your activity.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?actionBarSize"
    android:layout_alignParentTop="true"
    android:background="@color/colorPrimary"
    android:gravity="top"
    app:titleTextColor="@color/white">

    <ImageView
        android:id="@+id/iv_home"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:contentDescription="TODO"
        android:visibility="visible"
        app:srcCompat="@drawable/ic_back" />

    <TextView
        android:id="@+id/toolbar_title"
        style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="List Entry"
        android:textColor="@color/white"
        android:textSize="@dimen/large_text_size" />

    <ImageView
        android:id="@+id/iv_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_margin="@dimen/middium_padding"
        android:contentDescription="TODO"

        android:src="@mipmap/add"
        android:visibility="visible" />

</android.support.v7.widget.Toolbar>


</RelativeLayout>

and access you toolbar with framgment view.




回答2:


In this scenario you usually have:

  • Activity and layout that owns and contains Fragments, let us call them FragmentOwnerActivity.kt and fragment_owner_layout.xml
  • A class derived from Fragment and a layout associated with it, let us call them MyFragment.kt and my_fragment_layout.xml

To enable toolbars in your fragments you'll need to put the following to my_fragment_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:id="@+id/someid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MyFragment">

    <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="0dp"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_marginTop="0dp"
    >

        <android.support.v7.widget.Toolbar
                android:id="@+id/my_toolbar"
                android:layout_width="match_parent"
                android:layout_height="@attr/actionBarSize"
                android:background="@attr/colorPrimary"
                android:contentInsetEnd="0dp"
                android:contentInsetLeft="0dp"
                android:contentInsetRight="0dp"
                android:contentInsetStart="0dp"
                android:elevation="2dp"
                app:contentInsetEnd="0dp"
                app:contentInsetLeft="0dp"
                app:contentInsetRight="0dp"
                app:contentInsetStart="0dp"

        >

            <TextView
                    android:id="@+id/toolbar_title"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:text="@string/toolbar_title"
                    android:textSize="22sp"
                    android:textStyle="bold" />

        </android.support.v7.widget.Toolbar>

In MyFragment.kt you'll need to enable the toolbar:

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    (activity as AppCompatActivity).setSupportActionBar(view?.findViewById(R.id.my_toolbar))

In FragmentOwnerActivity.kt you'll need to inflate a fragment specific menu and process menu click events

// You'll need to create an xml with a menu for your fragment
// and then use it in inflate function below
override  fun onCreateOptionsMenu(menu: Menu): Boolean {
    menuInflater.inflate(R.menu.my_fragment_menu_id, menu)
    return true
}


override fun onOptionsItemSelected(item: MenuItem): Boolean {
    // Handle item selection
    when (item.getItemId()) {
        R.id.menu_item1_id -> {
            doMenuItem1()
            return true
        }
        R.id.menu_item2_id -> {
            doMenuItem2()
            return true
        }
        else -> return super.onOptionsItemSelected(item)
    }
}

Finally, you fragment_owner_layout.xml is just FrameLayout element that controls other frames

<?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:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MyFragmentOwner"/>


来源:https://stackoverflow.com/questions/48062260/add-an-actionbar-for-each-fragment

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