如何通过导航抽屉切换片段?

时间:2015-06-25 10:12:25

标签: android android-fragments navigation-drawer material-design

我有一个与导航抽屉相关的非常基本的问题。 我做了一个有导航抽屉的应用程序,但我不知道如何更改导航抽屉中项目选择的视图,但是我可以在每次点击时显示一个祝酒词,这意味着问题在于切换片段运行时。

这是我的主要代码:

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView; 
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity{

String TITLES[] = {"Home","Search","Recent Logs","My Wallet","Settings","Logout"};
int ICONS[] = {R.drawable.ic_action,R.drawable.ic_action_search,R.drawable.ic_action_logs,
        R.drawable.ic_action_wallet,R.drawable.ic_action_settings,R.drawable.ic_action_logout};
String NAME = "Akash Bangad";
String EMAIL = "akash.bangad@android4devs.com";
int PROFILE = R.drawable.default_user;
Toolbar toolbar;
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
DrawerLayout Drawer;
ActionBarDrawerToggle mDrawerToggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);
    mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
    mRecyclerView.setHasFixedSize(true);
    mAdapter = new MyAdapter(TITLES,ICONS,NAME,EMAIL,PROFILE);
    mRecyclerView.setAdapter(mAdapter);


    //Detect Gestures
    final GestureDetector mGestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {

        @Override public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

    });
    //Listen for clicks on navigation drawer
    mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
            View child = recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());
            if(child!=null && mGestureDetector.onTouchEvent(motionEvent) && recyclerView.getChildPosition(child)>0){
                Drawer.closeDrawers();
                Toast.makeText(MainActivity.this,TITLES[recyclerView.getChildPosition(child)-1], Toast.LENGTH_SHORT).show();
                selectItem(recyclerView.getChildPosition(child)-1);
                Fragment fragment;
                FragmentManager fragmentManager = getFragmentManager(); // For AppCompat use getSupportFragmentManager
                switch(recyclerView.getChildPosition(child)) {
                    default:
                    case 1:
                        fragment = new ProfileInfoFragment();
                        break;
                }
                fragmentManager.beginTransaction()
                        .replace(R.id.mainLayout, fragment)
                        .commit();
                return true;
            }
            return false;
        }
        @Override
        public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
        }
    });

    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);
    Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);
    mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.openDrawer,R.string.closeDrawer){

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }
    };
    Drawer.setDrawerListener(mDrawerToggle);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    mDrawerToggle.syncState();
}

public void selectItem(int i) {
    getSupportActionBar().setTitle(TITLES[i]);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    else if(mDrawerToggle.onOptionsItemSelected(item)){
        return true;
    }
    return super.onOptionsItemSelected(item);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mDrawerToggle.onConfigurationChanged(newConfig);
}
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="7dp">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/mainLayout">
    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar">
    </include>
</LinearLayout>


<android.support.v7.widget.RecyclerView
    android:id="@+id/RecyclerView"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="left"
    android:background="#ffffff"
    android:scrollbars="vertical">

</android.support.v7.widget.RecyclerView>

现在我创建了一个简单的片段,我希望应用程序在单击导航抽屉中的项目时切换到该片段。目前我正在用我的片段替换mainLayout,但这给了我ClassCastException。

Process: com.pocketcash.pocketcash, PID: 2456
java.lang.ClassCastException: com.pocketcash.pocketcash.MainActivity@c08ff73
        at com.pocketcash.pocketcash.ProfileInfoFragment.onAttach(ProfileInfoFragment.java:31)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:853)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
        at android.app.BackStackRecord.run(BackStackRecord.java:833)
        at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
        at android.app.FragmentManagerImpl$1.run(FragmentManager.java:447)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

1 个答案:

答案 0 :(得分:1)

如果您使用ActionBarActivity,则应使用支持库中的类:android.support.v4.app.FragmentManagerandroid.support.v4.app.Fragment而不是默认类。

因此,您必须将getFragmentManager()替换为getSupportFragmentManager(),将import android.app.Fragment;替换为import android.support.v4.app.Fragment;

浏览此文档Link