为每个片段添加一个操作栏

时间:2018-01-02 13:54:17

标签: android android-layout android-fragments nullpointerexception android-actionbar

假设我有4个片段放在mainActivity中,我想在每个片段中创建不同的动作栏。

当我按下片段1然后actionBar出现片段1,当我按下出现属于片段2的actoinbar的两个片段时

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)

这是我的活动:

    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;
    }
}

这是我的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>

2 个答案:

答案 0 :(得分:2)

在这种情况下,您通常有:

  • 拥有并包含片段的活动和布局,让我们将其称为FragmentOwnerActivity.kt和fragment_owner_layout.xml
  • 从Fragment派生的类以及与之关联的布局,我们称它们为MyFragment.kt和my_fragment_layout.xml

要在片段中启用工具栏,您需要将以下内容放入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>

在MyFragment.kt中,您需要启用工具栏:

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

在FragmentOwnerActivity.kt中,您需要为特定片段添加菜单并处理菜单单击事件

// 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)
    }
}

最后,您的fragment_owner_layout.xml只是控制其他框架的FrameLayout元素

<?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"/>

答案 1 :(得分:0)

是的,您可以将自定义工具栏添加到您的片段,并在Manifest中创建没有操作栏的活动主题,并执行类似的操作。此布局可能是您的片段布局,并在您的活动中膨胀。

<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>

并使用framgment视图访问工具栏。