Android新手,我有一个完美的导航抽屉。但是现在我想为每个选项插入图像 - 比如#34; home"另一个用于"扫描条形码"等。
我做了一些教程搜索,但无法找到合适的解决方案。有什么建议?提前谢谢。
NavigationDrawerFrag.xml
/**
* .
*
*/package com.androidatc.customviewindrawer;
//import android.support.v4.app.FragmentManager;
import android.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
//import android.support.v4.app.Fragment;
import android.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
loadFragmentLayout(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4),
getString(R.string.title_section5),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void loadFragmentLayout(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new MainViewFragment();
break;
case 1:
fragment = new BarCodeScanFrag();
break;
case 2:
fragment = new SearchBookFrag();
break;
case 3:
fragment = new MyAccFrag();
break;
case 4:
// fragment = new BorrowFrag();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerListView.setItemChecked(position, true);
mDrawerListView.setSelection(position);
mDrawerLayout.closeDrawer(Gravity.LEFT);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* @param fragmentId The android:id of this fragment in its activity's layout.
* @param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
// getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
//getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// it is for navigation menu
Fragment fragment = null;
if (mDrawerToggle.onOptionsItemSelected(item)) {
// Toast.makeText(getActivity(), "Inside Toggle", Toast.LENGTH_SHORT).show();
return true;
}
// below is not called for login. why?
// Toast.makeText(getActivity(), item.getItemId() + "=" + R.id.action_login + "B4 Action Login.", Toast.LENGTH_SHORT).show();
// if (item.getItemId() == R.id.action_logout) {
//// Toast.makeText(getActivity(), "Action Login.", Toast.LENGTH_SHORT).show();
// fragment = new LoginFrag();
//
// if (fragment != null) {
// FragmentManager fragmentManager = getFragmentManager();
// fragmentManager.beginTransaction()
// .replace(R.id.container, fragment).commit();
//
//
// }
//
// return true;
// }
// else {
// Toast.makeText(getActivity(), "Home .", Toast.LENGTH_SHORT).show();
// fragment = new HomeFrag();
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).commit();
}
return true;
}
// return super.onOptionsItemSelected(item);
// }
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
Fragment_navigation_drawer.xml
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#cccc"
tools:context=".NavigationDrawerFragment" />
答案 0 :(得分:3)
您必须为此案例制作自定义适配器。
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
@Override
public int getCount() {
return navDrawerItems.size();
}
@Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
}
如需完整参考,请访问以下链接: http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
答案 1 :(得分:1)
在此处设置ListView的数据,但不包含图像
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4),
getString(R.string.title_section5),
}));
如果要将图像添加到ListView,则需要创建一个自定义适配器,其中包含ListView
的图像。
试试Custom Listview with Image and Text using ArrayAdapter
答案 2 :(得分:1)
将此添加到您的主要活动:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<!-- REST OF YOUR CONTENT-->
<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:menu="@menu/drawer_menu"/>
</android.support.v4.widget.DrawerLayout>
抽屉布局应该是你的根元素:
在menu.xml文件夹中添加新菜单:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:id="@+id/menu" android:checkableBehavior="single">
<item
android:id="@+id/nav_home"
android:icon="@null"
android:title="Home" />
<item
android:id="@+id/nav_settings"
android:icon="@null"
android:title="Settings" />
<item
android:id="@+id/nav_playlists"
android:icon="@null"
android:title="PlayLists" />
</group>
</menu>
将此添加到您的主要活动onCreate
方法:
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
};
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
这样做:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
... Your Code....
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_settings:
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
break;
case R.id.nav_playlists:
Intent playlistsIntent = new Intent(this,PlayList.class);
startActivity(playlistsIntent);
break;
}
return false;
}
上面的代码表示实现导航项单击侦听器并覆盖该方法。那就是它!
答案 3 :(得分:1)
你可以查看我已经实现了这个Github Link的github链接,或者你也可以按照一系列的slidenerd教程Android RecyclerView Example Part 1: Android Material Design Tutorials来实现你想要实现的目标
答案 4 :(得分:1)
在这里,我可以轻松地分享一些简单的编辑。
只需编辑nav_header_main.xml
即可
<Button
android:id="@+id/btn_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="3dp"
android:background="@null"
android:drawablePadding="6dp"
android:drawableRight="@mipmap/grocery_logo"
android:gravity="left|center"
android:padding="6dp"
android:text="Home"
android:textColor="@color/colorPrimary" />
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/border" />
<LinearLayout
android:id="@+id/nav_quicklist_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<ImageView
android:layout_width="50dp"
android:layout_height="51dp"
android:layout_weight="0.05"
android:src="@mipmap/quicklist_menu" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:text="Quick List"
android:textAlignment="center"
android:textColor="@color/menu_text_color"
android:textSize="13sp" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/border" />
<LinearLayout
android:id="@+id/nav_myaccount_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<ImageView
android:layout_width="50dp"
android:layout_height="51dp"
android:layout_weight="0.05"
android:src="@mipmap/my_account" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:text="My Account"
android:textAlignment="center"
android:textColor="@color/menu_text_color"
android:textSize="13sp" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/border" />
在MainActivity.java类中使用它来获得设计。
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
for (int i = 0; i < navigationView.getMenu().size(); i++) {
MenuItem item = navigationView.getMenu().getItem(i);
if (i != 2) {
Drawable dr = item.getIcon();
System.out.println(i + "-----drawable..." + dr);
Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
Drawable d = new BitmapDrawable(getResources(), Bitmap.createBitmap(bitmap, 0, 0, 72, 72));
navigationView.getMenu().getItem(i).setIcon(d);
}
LinearLayout lay = (LinearLayout) navigationView.getHeaderView(0);
Button btn_home = (Button) lay.findViewById(R.id.btn_home);
btn_home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragment = new Home();
if (fragment != null) {
title_tv.setText("Grocery");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
});
LinearLayout nav1 = (LinearLayout) lay.findViewById(R.id.nav_quicklist_layout);
nav1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragment = new CreateQuickList();
if (fragment != null) {
title_tv.setText("SRSGrocery");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
});
LinearLayout nav2 = (LinearLayout) lay.findViewById(R.id.nav_myaccount_layout);
nav2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragment = new MyAccount();
if (fragment != null) {
title_tv.setText("SRSGrocery");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
});
答案 5 :(得分:1)
这是您必须在抽屉列表视图上设置的基础适配器类
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
@Override
public int getCount() {
return navDrawerItems.size();
}
@Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
查找here
的完整代码答案 6 :(得分:1)
当您将图像放入导航抽屉时,您必须声明布局,在本例中为relativeLayout。 在布局xml中,您声明了一个布局,现在您将图像放在布局中,然后放入listView。
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- main content -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<!-- Menu -->
<RelativeLayout
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@drawable/degradee"
android:orientation="vertical" >
<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@drawable/theworldisyours" />
<ListView
android:id="@+id/list_view_drawer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/image_view"
android:choiceMode="singleChoice" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
现在在你的活动中
public class MainActivity extends ActionBarActivity {
private String[] mOptionMenu;
private DrawerLayout mDrawerLayout;
private RelativeLayout mDrawerRelativeLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitleSection;
private CharSequence mTitleApp;
private Fragment mFragment = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mOptionMenu = new String[] { getString(R.string.first_fragment),
getString(R.string.second_fragment),
getString(R.string.third_fragment) };
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerRelativeLayout = (RelativeLayout) findViewById(R.id.left_drawer);
mDrawerList = (ListView) findViewById(R.id.list_view_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(getSupportActionBar()
.getThemedContext(), android.R.layout.simple_list_item_1,
mOptionMenu));
initContentWithFirstFragment();
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
mFragment = new FirstFragment();
break;
case 1:
mFragment = new SecondFragment();
break;
case 2:
mFragment = new ThirdFragment();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, mFragment).commit();
mDrawerList.setItemChecked(position, true);
mTitleSection = mOptionMenu[position];
getSupportActionBar().setTitle(mTitleSection);
mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
}
});
mDrawerList.setItemChecked(0, true);
mTitleSection = getString(R.string.first_fragment);
mTitleApp = getTitle();
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(R.string.app_name);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(this, R.string.action_settings, Toast.LENGTH_SHORT)
.show();
;
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void initContentWithFirstFragment(){
mTitleSection =getString(R.string.first_fragment);
getSupportActionBar().setTitle(mTitleSection);
mFragment = new FirstFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, mFragment).commit();
}
}
您可以查看this post和此example in GitHub
答案 7 :(得分:0)