导航抽屉没有显示片段

时间:2017-01-08 11:34:12

标签: android navigation-drawer

当用户点击导航抽屉中的任何项目时,我正在尝试显示不同的片段。我无法显示片段。我没有收到任何错误消息。它只是没有显示片段。

布局:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- The main content view -->


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/main_content"
    android:orientation="vertical">

    <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:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/notes_list"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


</LinearLayout>

    <!-- The navigation drawer -->
    <ListView android:id="@+id/navigationitems"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:background="@android:color/darker_gray"
        android:dividerHeight="0dp"
        />
</android.support.v4.widget.DrawerLayout>


MainActivity:

package com.example.note.pankajpc.note;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import io.realm.Case;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
import io.realm.Sort;

public class MainActivity extends AppCompatActivity {

    private ListView mNavigationItem;
    private DrawerLayout mDrawerLayout;
    private FrameLayout mMainContent;
    Intent intent;
    String [] mNavigationItemArray;
    List <DrawerItem> mDrawerItem = new ArrayList();
    private ActionBarDrawerToggle mDrawerToggle;
    private RecyclerView mRecyclerView;
    private static NoteAdapter mNoteAdapter;
    private static Realm mRealm;
    private static Context context1;
    private RealmResults<NoteModel> mResults;
    SearchView mSearchView;
    String mSearchString=null;
    private ContextMenu contextMenu;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);
        Realm.init(this);
        context1 = this;
       // initAlarm();
        mRealm = Realm.getDefaultInstance();
        //initialize relam database
        initUi();
        initDrawerItem();


        mRecyclerView = (RecyclerView)findViewById(R.id.notes_list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        mNoteAdapter = new NoteAdapter(this,mResults,mRealm);
        mRecyclerView.setAdapter(mNoteAdapter);
        mNavigationItemArray = getResources().getStringArray(R.array.navigation_list);
        mNavigationItem = (ListView)findViewById(R.id.navigationitems);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_navigation);


        mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.app_name,R.string.app_name){

        };
        mDrawerLayout.addDrawerListener(mDrawerToggle);



        //setting custom adapter on Navigation Drawer
        mNavigationItem.setAdapter(new CustomDrawerAdapter(this,R.layout.custom_navigation_listview_row,mDrawerItem));

        //setting onClick Listener on Navigation Drawer
        mNavigationItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Fragment fragment = null;
                mDrawerLayout.closeDrawers();

                switch (mDrawerItem.get(i).getItemName()){
                    case "Add a Note":
                        intent = new Intent(MainActivity.this,AddNote.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        break;
                    case "Settings":
                        Toast.makeText(MainActivity.this,"test1",Toast.LENGTH_SHORT).show();
                        Fragment fragment1 = new TestFragment();
                        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                        ft.add(R.id.main_content, fragment1);
                        ft.commit();

                        break;
                }


            }
        });

    }

    private void initAlarm() {

        Intent i = new Intent(this,AlarmReceiver.class);
      PendingIntent  alarmIntent = PendingIntent.getBroadcast(this, 0, i, 0);
        AlarmManager am = (AlarmManager)this.getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,200,200,alarmIntent);
    }

    private void initDrawerItem() {
        mDrawerItem.add(new DrawerItem("Notes",R.drawable.ic_notes));
        mDrawerItem.add(new DrawerItem("Add a Note",R.drawable.ic_add));
        mDrawerItem.add(new DrawerItem("Search",R.drawable.ic_search));
        mDrawerItem.add(new DrawerItem("Trash",R.drawable.ic_trash));
        mDrawerItem.add(new DrawerItem("Settings",R.drawable.ic_settings));
    }


    private void initUi() {
        mResults = mRealm.where(NoteModel.class).findAllSortedAsync("mNoteDateTime");

    }


   protected void onStart() {
       super.onStart();
       this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
       mResults.addChangeListener(new RealmChangeListener<RealmResults<NoteModel>>() {
           @Override
           public void onChange(RealmResults<NoteModel> element) {
               mNoteAdapter.update(mResults);


           }
       });
   }

    @Override
    //This override displays the items when action bar up button click
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        //handling the menu clicks on menu.xml
        switch (id){
            case R.id.actionAdd:
                startActivity((new Intent(context1,AddNote.class)).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP));
                break;
            case R.id.dateCreated:
                mResults = mRealm.where(NoteModel.class).findAllSorted("mNoteDateTime");
                mNoteAdapter.update(mResults);
                break;
            case R.id.alphabetically:
                mResults = mRealm.where(NoteModel.class).findAllSorted("mNoteTitle");
                mNoteAdapter.update(mResults);
                break;
            case R.id.priority:
                mResults = mRealm.where(NoteModel.class).findAllSorted("mNotePriority", Sort.DESCENDING);
                mNoteAdapter.update(mResults);
                break;
        }

        return true;
    }




    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {

        getMenuInflater().inflate(R.menu.menu, menu);
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        mSearchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));


        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }


            @Override
            public boolean onQueryTextChange(String newText) {
                String query = newText.toLowerCase();
                mResults = mRealm.where(NoteModel.class).contains("mNoteTitle", query, Case.INSENSITIVE).findAllSorted("mNoteDateTime");
                mNoteAdapter.update(mResults);
                return false;

            }
        });

        return true;

    }

    @Override
    protected void onStop() {
        super.onStop();
        resetSearchView();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        resetSearchView();
    }

    private void resetSearchView() {
        mSearchView.clearFocus();
        mSearchView.setQuery("", false);
        mSearchView.setFocusable(false);
        mSearchView.onActionViewCollapsed();
    }


}

片段:

package com.example.note.pankajpc.note;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Pankaj PC on 01-08-2017.
 */

public class TestFragment extends Fragment {

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

1 个答案:

答案 0 :(得分:1)

你不能使用Linearlayout存储你的片段,它需要是你需要添加片段的Framelayout

这就是我总是设置导航抽屉的方法:

<?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/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize" />
        </android.support.design.widget.AppBarLayout>

        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/appbar_layout" />
    </RelativeLayout>

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

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