问题
how can i add an image header to my navigation drawer layout like this one
and this is my code : MainActivity.java
package com.webileapps.navdrawer;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.webileapps.navdrawer.House_Fragment.Garage_Fragment;
import com.webileapps.navdrawer.House_Fragment.Hall_Fragment;
import com.webileapps.navdrawer.House_Fragment.Kitchen_Fragment;
import com.webileapps.navdrawer.menu.Settings.AccountPreference;
import com.webileapps.navdrawer.menu.Settings.DialogChangeAccount;
import com.webileapps.navdrawer.menu.Settings.DialogChangeCity;
import com.webileapps.navdrawer.menu.Settings.DialogSettingsApp;
import com.webileapps.navdrawer.menu.Settings.DialogSupport;
import com.webileapps.navdrawer.menu.Settings.CityPreference;
import com.webileapps.navdrawer.menu.Settings.DialogueConnexion;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends SherlockFragmentActivity
implements DialogChangeCity.dialogDoneListenerCity,
DialogChangeAccount.dialogDoneListenerAccount,
DialogSettingsApp.dialogDoneListenerSett,
DialogSupport.dialogDoneListenerSupp,
DialogueConnexion.dialogDoneListenerConn {
DrawerLayout mDrawerLayout;
DrawerLayout mDrawerLayoutR;
ExpandableListView mDrawerList;
ExpandableListView mDrawerListR;
ActionBarDrawerToggle mDrawerToggle;
ActionBarDrawerToggle mDrawerToggleR;
private CharSequence mDrawerTitle;
private CharSequence mDrawerTitleR;
private CharSequence mTitle;
private CharSequence mTitleR;
List<Model> listDataHeader;
List<Model> listDataHeaderR;
HashMap<Model, List<Model>> listDataChild;
ExpandableListAdapter listAdapter;
ExpandableListAdapter listAdapterR;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mTitleR = mDrawerTitleR = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.left_drawer);
mDrawerListR = (ExpandableListView) findViewById(R.id.right_drawer);
prepareListData();
prepareListDataRight();
// set a custom shadow that overlays
the main content when the drawer opens
listAdapter = new ExpandableListAdapter(this,
listDataHeader, listDataChild);
listAdapterR = new ExpandableListAdapter(this, listDataHeaderR,null);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// mDrawerLayout.setDrawerShadow(R.drawable.up_24,GravityCompat.END);
// set up the drawer's list view with items and click listener
/* mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mRoomTitles));*/
mDrawerList.setAdapter(listAdapter);
mDrawerListR.setAdapter(listAdapterR);
//mDrawerList.setOnItemClickListener(
new DrawerItemClickListener());
mDrawerListR.setOnGroupClickListener(new ExpandableListView.
OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView expandable
ListView,
View view, int i, long l) {
switch(i){
case 0:
DialogSettingsApp dialogSettingsApp =
new DialogSettingsApp();
dialogSettingsApp.
show(getFragmentManager(),"diagSett");
break;
case 1:
DialogChangeAccount dialogChangeAccount =
new DialogChangeAccount();
dialogChangeAccount.
show(getFragmentManager(),"diagA");
break;
case 2:
DialogChangeCity dialogChangeCity =
new DialogChangeCity();
dialogChangeCity.show(getFragmentManager(),"diagC");
break;
case 3:
DialogSupport dialogSupport = new DialogSupport();
dialogSupport.show(getFragmentManager(),"diagSupp");
break;
case 4:
DialogueConnexion dialogueConnexion =
new DialogueConnexion();
dialogueConnexion.
show(getFragmentManager(),"diagConn");
break;
}
return false;
}
});
mDrawerList.setOnGroupClickListener(new ExpandableListView.
OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
Fragment frg = null;
switch (groupPosition) {
case 0:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, PageSlidingHomeFragment.newInstance()
, PageSlidingHomeFragment.TAG).commit();
mDrawerList.setItemChecked(groupPosition, true);
mDrawerList.setSelection(groupPosition);
mDrawerLayout.closeDrawer(mDrawerList);
break;
case 1:
break;
case 2:
frg = new Kitchen_Fragment();
break;
case 3:
frg = new Garage_Fragment();
break;
case 4:
frg = new Hall_Fragment();
break;
}
if (frg != null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.content, frg).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(groupPosition, true);
mDrawerList.setSelection(groupPosition);
mDrawerLayout.closeDrawer(mDrawerList);
}
return false;
}
});
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggleR=new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.down_24,
R.string.drawer_open,
R.string.drawer_close
){
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitleR);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /*
nav drawer image to replace 'Up' caret */
R.string.drawer_open, /*
"open drawer" description for accessibility */
R.string.drawer_close /*
"close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.setDrawerListener(mDrawerToggleR);
if (savedInstanceState == null) {
selectItem(0);
}
}
@Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu){
com.actionbarsherlock.view.MenuInflater
inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
mDrawerLayout.closeDrawer(mDrawerListR);
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
break;
}
case R.id.action_contact:{
mDrawerLayout.closeDrawer(mDrawerList);
if (mDrawerLayout.isDrawerOpen(mDrawerListR)) {
mDrawerLayout.closeDrawer(mDrawerListR);
} else {
mDrawerLayout.openDrawer(mDrawerListR);
}
break;
}
}
return super.onOptionsItemSelected(item);
}
public void showInputDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Change city");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("Go", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
changeCity(input.getText().toString());
}
});
builder.show();
}
public void changeCity(String city) {
new CityPreference(this).setCity(city);
}
// The click listener for ListView in the navigation drawer
/*private class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view
, int position,long id) {
selectItem(position);
}
}
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(int position) {
switch (position) {
case 0:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content,
PageSlidingHomeFragment.newInstance(),
PageSlidingHomeFragment.TAG).commit();
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
private void prepareListDataRight(){
listDataHeaderR = new ArrayList<Model>();
listDataHeaderR.add(new Model(R.drawable.settings_24,
"App Settings"));
listDataHeaderR.add(new Model(R.drawable.edit_user_24,
"Update Account"));
listDataHeaderR.add(new Model(R.drawable.edit_24, "Change City"));
listDataHeaderR.add(new Model(R.drawable.quest_24, "Support"));
listDataHeaderR.add(new Model(R.drawable.
ic_action_user, "Disconnection"));
}
private void prepareListData() {
listDataHeader = new ArrayList<Model>();
listDataChild = new HashMap<Model, List<Model>>();
// Adding child data
listDataHeader.add(new Model(R.drawable.home24, "Home"));
listDataHeader.add(new Model("Rooms"));
listDataHeader.add(new Model(R.drawable.kitchen_24, "Kitchen"));
listDataHeader.add(new Model(R.drawable.garage_24, "Garage"));
listDataHeader.add(new Model(R.drawable.room_24, "Hall"));
// Adding child data
List<Model> home = new ArrayList<Model>();
home.add(new Model(R.drawable.settings_24, "Settings"));
home.add(new Model(R.drawable.devices_24, "Devices"));
home.add(new Model(R.drawable.weather_24, "Weather"));
List<Model> rooms = new ArrayList<Model>();
rooms.add(new Model(R.drawable.bed_c_24, "1sr Child room"));
rooms.add(new Model(R.drawable.bed_c_24, "2sd Child room"));
rooms.add(new Model(R.drawable.bedroom_24, "Parents room"));
rooms.add(new Model(R.drawable.hotel_24, "Guests room"));
rooms.add(new Model(R.drawable.dining_room_24, "Dining room"));
rooms.add(new Model(R.drawable.livingroom_24, "Living room"));
rooms.add(new Model(R.drawable.office_24, "Office"));
rooms.add(new Model(R.drawable.bathroom_24, "Bathroom 1st floor"));
rooms.add(new Model(R.drawable.bathroom_24, "Bathroom 2nd floor"));
// Header, Child data
listDataChild.put(listDataHeader.get(1), rooms);
}
@Override
public void onDone(String text, boolean state) {
if (state) {
changeCity(text);
//this.recreate();
restartSelf();
}
}
private void restartSelf() {
AlarmManager am = (AlarmManager) gettSystemService(Context.
ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,Calendar.getInstance()
.getTimeInMillis()
+ 1000, // one second
PendingIntent.getActivity(this, 0, getIntent(),
PendingIntent.FLAG_ONE_SHOT
| PendingIntent.FLAG_CANCEL_CURRENT));
finish();
}
@Override
public void onDoneA(String login, String opwd, String npwd) {
if(login!="" && opwd!="" && npwd!=""){
changeAccount(login,opwd,npwd);
}
}
private void changeAccount(String login, String opwd, String npwd) {
new AccountPreference(this).setAccountL(login);
new AccountPreference(this).setAccountOP(opwd);
new AccountPreference(this).setAccountNP(npwd);
}
@Override
public void onDone() {
int x = 0;
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas
.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
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:id="@+id/content"
android:layout_height="match_parent" >
</RelativeLayout>
<!-- The navigation drawer -->
<ExpandableListView
android:id="@+id/left_drawer"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#000"
android:choiceMode="singleChoice"
android:divider="@color/abs__bright_foreground_disabled_holo_dark"
android:dividerHeight="2dp" />
<ExpandableListView
android:id="@+id/right_drawer"
android:layout_width="200dp"
android:layout_height="300dp"
android:layout_gravity="end"
android:background="#000"
android:choiceMode="singleChoice"
android:divider="@color/abs__bright_foreground_disabled_holo_dark"
android:dividerHeight="2dp" />
</android.support.v4.widget.DrawerLayout>
ExpandableListAdapter.java
package com.webileapps.navdrawer;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<Model> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<Model, List<Model>> _listDataChild;
public ExpandableListAdapter(Context context, List<Model> listDataHeader,
HashMap<Model, List<Model>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
@Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this.
_listDataHeader.get(groupPosition)).get(childPosititon);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final Model childText = (Model) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
ImageView IconListChild = (ImageView) convertView.findViewById
(R.id.item_icon_child);
IconListChild.setImageResource(childText.getIcon());
txtListChild.setText(childText.getTitle());
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
int i=0;
switch (groupPosition) {
case 1:
i= this._listDataChild.get
(this._listDataHeader.get(groupPosition)).size();
break;
default:
i=0;
break;
}
return i;
}
@Override
public Model getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
@Override
public int getGroupCount() {
return this._listDataHeader.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
Model headerTitle = (Model) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
ImageView IconListHeader = (ImageView) convertView.findViewById
(R.id.item_icon_group);
IconListHeader.setImageResource(headerTitle.getIcon());
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle.getTitle());
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
回答1:
In the Navigation Drawer layout xml file. Above drawerView and inside your parent layout add an image view as shown below:
<ImageView
android:id="@+id/image"
android:layout_width="280dp"
android:layout_height="140dp"
android:src="respective_source_of_image" />
This should be sufficient. Hope this helps.
Use Recycler View to create a navigation drawer. Recycler view is used most now. In your navigation drawer fragment have your layout file as shown below. This make you achieve your objective:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ms.t.tms.NavigationDrawerFragment">
<ImageView
android:id="@+id/image"
android:layout_width="280dp"
android:layout_height="140dp"
android:src="respective_image_src" />
<android.support.v7.widget.RecyclerView
android:id="@+id/drawerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/image"
android:background="@color/colorPrimary"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
回答2:
You can simply do it following this sample :
<?xml version="1.0" encoding="utf-8"?>
<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">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- insert you main view childs here -->
</FrameLayout>
<!-- The navigation drawer -->
<LinearLayout
android:layout_width="240dp"
android:layout_gravity="end"
android:background="@color/colorPrimary"
android:orientation="vertical"
android:layout_height="match_parent">
<ImageView
android:layout_width="240dp"
android:layout_height="140dp"
android:src="@drawable/logo" />
<ListView
android:id="@+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="end"
android:choiceMode="singleChoice"
android:background="@color/colorPrimary"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
You will have your image added before the listview. You can manage your view like any other view.
Hope it will help you ;)
来源:https://stackoverflow.com/questions/29029070/can-i-add-an-image-header-in-navigation-drawer-layout