如何在Fragment中实现自定义工具栏

时间:2018-05-05 17:35:54

标签: android android-fragments

我阅读了很多文章并观看了很多视频,但我仍然不知道如何在片段中设置操作栏。我有一个带有自定义工具栏的活动X和左上角的一个导航视图(工具栏在xml文件中分隔),我将其导入xml中的活动X.

这是我的工具栏中的一个xml:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawerChooser"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/new_gradients"
    android:fitsSystemWindows="true"
    tools:context=".ChoosingActivity">
    <!--tools:openDrawer="start"-->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            android:elevation="4dp"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    </LinearLayout>

    <FrameLayout
        android:id="@+id/fragment_container_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/header"
        app:menu="@menu/drawer_menu">

    </android.support.design.widget.NavigationView>


</android.support.v4.widget.DrawerLayout>

编辑,新工具栏:

<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"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@drawable/new_gradients"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/new_gradients"
        android:fitsSystemWindows="true"
        tools:context=".ChoosingActivity">


        <FrameLayout
            android:id="@+id/fragment_container_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </android.support.v4.widget.DrawerLayout>


    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/header"
        app:menu="@menu/drawer_menu">

    </android.support.design.widget.NavigationView>
    </LinearLayout>
</LinearLayout>

这是我的活动X:

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class ChoosingActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawer;



    public void userChoosed(View view) {


        Intent choosedIntent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(choosedIntent);

    }

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

        Toolbar toolbar = findViewById(R.id.toolbarxml);
        setSupportActionBar(toolbar);

        drawer = findViewById(R.id.drawerChooser);

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Item will be Selected
        switch (item.getItemId()) {
            case R.id.nav_meetings:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Ausstehende_Treffen_Fragment()).commit();
                break;
            case R.id.nav_finished_meetings:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Abgeschlossene_Treffen_Fragment()).commit();
                break;
            case R.id.nav_rate:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Treffen_Bewerten_Fragment()).commit();
                break;
            case R.id.nav_edit_profile:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Profil_Bearbeiten_Fragment()).commit();
                break;
            case R.id.nav_settings:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Einstellungen_Fragment()).commit();
                break;
        }

        drawer.closeDrawer(GravityCompat.START);

        return true;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}

编辑,新活动X(查看我的评论“Toolbar_chooser或工具栏”):

public class ChoosingActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawer;



    public void userChoosed(View view) {


        Intent choosedIntent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(choosedIntent);

    }

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

        Toolbar toolbar = findViewById(R.id.toolbar_chooser); // Toolbar_chooser or toolbar?
        setSupportActionBar(toolbar);

        drawer = findViewById(R.id.drawerChooser);

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Item will be Selected
        switch (item.getItemId()) {
            case R.id.nav_meetings:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Ausstehende_Treffen_Fragment()).commit();
                break;
            case R.id.nav_finished_meetings:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Abgeschlossene_Treffen_Fragment()).commit();
                break;
            case R.id.nav_rate:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Treffen_Bewerten_Fragment()).commit();
                break;
            case R.id.nav_edit_profile:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Profil_Bearbeiten_Fragment()).commit();
                break;
            case R.id.nav_settings:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Einstellungen_Fragment()).commit();
                break;
        }

        drawer.closeDrawer(GravityCompat.START);

        return true;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}

在这里我的Fragment我想在工具栏中添加导航视图:

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

public class Ausstehende_Treffen_Fragment extends Fragment {


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ausstehende_treffen,container,false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        ((AppCompatActivity)getActivity()).getSupportActionBar(toolbar); // HOW???

    }
}

编辑,新片段:

public class Ausstehende_Treffen_Fragment extends Fragment {

   // Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbarreal);


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ausstehende_treffen,container,false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Toolbar toolbar = ((ChoosingActivity)getActivity()).findViewById(R.id.toolbar_ausstehende_treffen);

    }
}

这里也是片段的xml,我想要工具栏:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_orange_light">

    <include
        android:id="@+id/toolbar_ausstehende_treffen"
        layout= "@layout/toolbar"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ausstehende Treffen Fragment"
        android:textSize="25sp"
        android:layout_centerInParent="true"/>

</RelativeLayout>

我无法再在我选择的活动中打开导航栏,我不知道为什么......

我在xml文件中手动包含工具栏,这是必要的吗? +片段本身的一些代码。男人,我希望你理解我的代码和我的问题。请帮助我,我只想将自定义工具栏保留在任何片段和活动中。

请帮助我,它如此令人沮丧,浪费了这么多小时只有一个工具栏,已经存在..

3 个答案:

答案 0 :(得分:0)

尝试在您的活动中添加工具栏:

    mTopToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(mTopToolbar);

获取拥有该片段的Activity(Fragment.getActivity())并设置其ActionBar属性。

然后,在将工具栏设置为ActionBar以获取后退/上移按钮后,juse使用您在ActionBar中提到的相同setDisplayHomeAsUpEnabled方法。

从片段访问它的示例:

((AppCompatActivity)getActivity()).getSupportActionBar().setSubtitle();

希望它有所帮助。

答案 1 :(得分:0)

就这么简单。

Toolbar toolbar = ((ChoosingActivity)getActivity()).findViewById(R.id.toolbar);

现在做任何你想做的事;)。

答案 2 :(得分:0)

这可能是因为Toolbar中的所有其他内容都涵盖了DrawerLayout。尝试交换LinearLayoutDrawerLayout,以便垂直LinearLayout是您的根布局,如下所示:

<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"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawerChooser"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/new_gradients"
    android:fitsSystemWindows="true"
    tools:context=".ChoosingActivity">


    <FrameLayout
     android:id="@+id/fragment_container_toolbar"
     android:layout_width="match_parent"
     android:layout_height="match_parent" />

</android.support.v4.widget.DrawerLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/header"
    app:menu="@menu/drawer_menu">

</android.support.design.widget.NavigationView>


</LinearLayout>

大概就是这样,关键是你的Toolbar必须在DrawerLayout之外。

相关问题