【问题标题】:Replace NavigationView with Fragments用片段替换 NavigationView
【发布时间】:2016-10-19 04:24:25
【问题描述】:

我正在用 Fragment 替换 NavigationView,并进一步使用视图。 (因为 NavigationView 是 FrameLayout 的子级)

单击 NavView 中的任何项目时.. 我用片段覆盖 NavView。如果有人点击后退按钮.. 我想回到 NavView。

在用 Fragment 替换 NavigationView 时,我放了一个工具栏。

问题

一个。工具栏显示一个“返回”链接 - 但它不起作用。

b.工具栏显示“设置”菜单 - 我不想在片段上显示这个。但是..我仍然想要 MainActivity 工具栏上的“设置”菜单。

c。工具栏似乎与状态栏重叠 - 如何将工具栏放在片段中的状态栏下方。

已尝试的选项

一个。 MainActivity 的 OnBackPressed 方法 - fragmentManager.popUpStack()

b. Fragment的onOptionsItemSelected()方法-fragmentManager.popUpStack()

c。在工具栏上创建了一个监听器,在 onClick 方法中:fragmentManager.popUpStack()

截图:

这是我的代码:

MainActivity:> onNavigationItemSelected()

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    ItemsFragment fragment = new ItemsFragment();
    android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.nav_view, fragment);
//                fragmentTransaction.setTransition();
    fragmentTransaction.addToBackStack("LeftMainNavDrawer");
    fragmentTransaction.commit();

//        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//        drawer.closeDrawer(GravityCompat.START);
    return true;
}

片段

package com.example.deep_kulshreshtha.expandablelistnavdrawer;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.deep_kulshreshtha.expandablelistnavdrawer.dummy.DummyContent;
import com.example.deep_kulshreshtha.expandablelistnavdrawer.dummy.DummyContent.DummyItem;

import java.util.List;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class ItemsFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private OnListFragmentInteractionListener mListener;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ItemsFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static ItemsFragment newInstance(int columnCount) {
        ItemsFragment fragment = new ItemsFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }

        setHasOptionsMenu(false);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_item_list, container, false);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list);

        // Set the adapter
//        if (view instanceof RecyclerView) {
            Context context = view.getContext();
//            RecyclerView recyclerView = (RecyclerView) view;

            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }

            recyclerView.setAdapter(new MyItemRecyclerViewAdapter(DummyContent.ITEMS, mListener));
//        }

        Toolbar toolbar = (Toolbar) view.findViewById(R.id.itemsToolbarNavDrawer);
        /*toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "Inside Toolbar click", Toast.LENGTH_LONG).show();
            }
        });*/
        AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity();
        appCompatActivity.setSupportActionBar(toolbar);
        appCompatActivity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        appCompatActivity.getSupportActionBar().setDisplayShowHomeEnabled(true);

        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.removeItem(R.id.action_settings);
        super.onCreateOptionsMenu(menu, inflater);
    }

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

    @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 OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(DummyItem item);
    }
}

片段布局文件

<LinearLayout 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:orientation="vertical"
    android:layout_height="match_parent"
    android:layout_width="match_parent" >

    <android.support.v7.widget.Toolbar
        android:id="@+id/itemsToolbarNavDrawer"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

    <android.support.v7.widget.RecyclerView

        android:id="@+id/list"
        android:name="com.example.deep_kulshreshtha.expandablelistnavdrawer.ItemsFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:layoutManager="LinearLayoutManager"
        tools:context="com.example.deep_kulshreshtha.expandablelistnavdrawer.ItemsFragment"
        tools:listitem="@layout/fragment_item"
        android:background="@android:color/white"/>

</LinearLayout>

【问题讨论】:

    标签: android android-fragments android-toolbar navigationview


    【解决方案1】:

    在您的主要活动中添加 1 个框架布局并将其 id 作为容器。然后在你的java代码中

    fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.main_container,new HomeFragment());
            fragmentTransaction.commit();

    使用片段事务将该容器替换为您希望在应用启动时默认显示为主页的一个框架。

    然后在每个片段中使用这个容器来替换

    【讨论】:

    • 想法是用片段替换 NavigationView - 这是可行的。什么不起作用是......从 Fragment 到 NavigationView 的后退按钮。
    • fragmentTransaction.addToBackStack("null");
    • 是的,它没有帮助。我想了解的是.....如果我们从 Fragment 按下后退按钮 -> 我们可以转到原来的 FrameLayout 吗??
    • 是的,我们可以,但我以不同的方式做到了这一点。它的主要活动。我给了空容器,每当我执行交易时,我都会用我想要的片段替换容器。
    【解决方案2】:

    我想出了一个解决方案 .. 看起来“工具栏”类为整个应用程序提供了一个实例。

    当我使用 Activity 的 onOptionsItemSelected 方法时...我得到了控制。在这里我可以 popUpStack() 并转到 NavigationView。

    #

    尚未弄清楚如何将布局保持在状态栏下方。 : android:fitsSystemWindows="true" ... 似乎没有工作。

    【讨论】:

      猜你喜欢
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      相关资源
      最近更新 更多