用Fragments替换NavigationView

时间:2016-10-19 04:24:26

标签: android android-fragments android-toolbar navigationview

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

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

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

问题

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

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

℃。工具栏似乎与StatusBar重叠 - 如何将工具栏放在StatusBar下面的片段中。

尝试了选项

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

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

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

截图: enter image description here enter image description here

这是我的代码:

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

FragmentLayout文件

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

2 个答案:

答案 0 :(得分:0)

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

function getPhoto($con,$dest)
    {
        $user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" ); //added

        $result = mysqli_query($con,"SELECT * FROM `profile_img` where `user_id` = '$user_id' ORDER BY `id` DESC LIMIT 1");

        if($row = mysqli_fetch_array($result))
            return $row;

        return 0;
    }


// Make sure all functions above are include here

// Get the database connection
$con        =   Connection();
// Check for post   
if(isset($_POST['create'])) {
        // Try uploading
        $upload =   UploadFile($_FILES);
        // If upload fails
        if(!$upload['success'])
            echo '<h3>Sorry, an error occurred</h3>';
        else {
                // You could add error handling here based on the results of 
                // each function's success or failure below.

                // Try to save it
                $saveToDb   =   SaveToDb($con,$upload['file']['dest']);
                // Get the profile from image name
                $profPic    =   ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false; ?>


                <?php
            }
    }
?>
<img id="profile-pic" src="<?php echo (!empty($profPic) && $profPic != 0)? $profPic['img'] : "profile_images/default.jpg"; ?>" alt="<?php echo (!empty($profPic) && $profPic != 0)? "Profile Picture" : "No Picture"; ?>" />
<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" class="inputbarfile" onchange="readURL(this);">
    <img width="400px" height="300px" id="file" src="#" alt="your image">
    <input type="submit" name="create" id="signinButton" value="Upload">
</form>

使用片段事务将具有一个片段的容器替换为您要在app start as home上显示为默认值的片段。

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

答案 1 :(得分:0)

我找到了一个解决方案..看起来像工具栏&#39; class有整个应用程序的一个实例。

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

然而要弄清楚如何将布局保持在StatusBar之下。 :android:fitsSystemWindows =&#34; true&#34; ......似乎没有用。