我在我的项目中实现了导航抽屉。一切都很好,项目全部设置。我的抽屉只有一个问题。点击每个项目我有子项但我不想在展开中显示它列表视图,我想在我的主导航抽屉旁边打开另一个包含子项目的子抽屉。我该怎么办。请帮助。
上下文中的代码
MainActivity
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
private String[] mTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initToolbar();
mTitles=getResources().getStringArray(R.array.drawer_titles);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList=(ListView)findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(
this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
private void initToolbar() {
toolbar=(Toolbar)findViewById(R.id.toolbar);
toolbar.setTitle(R.string.toolbar_title);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_drawer);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content
}
}
main.xml中
<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:id="@+id/toolbar"
android:background="#efeaea"
android:layout_height="50dp"/>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_below="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<LinearLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:dividerHeight="2dp"
android:background="#ffffff"/>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
答案 0 :(得分:1)
您可以实现自定义可扩展适配器
list_item.xml //组内的子视图
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="55dip"
android:orientation="vertical"
android:divider="@color/black">
<TextView
android:id="@+id/lblListItem"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="@dimen/textSize14"
android:typeface="sans"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:layout_marginLeft="80dp"/>
</LinearLayout>
list_group.xml //父视图
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:padding="3dp"
android:dividerPadding="10dp">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="@+id/navImage"
android:layout_margin="@dimen/padding_10dp"
android:layout_gravity="center"/>
<TextView
android:id="@+id/lblListHeader"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="left|center"
android:layout_weight=".5"
android:textSize="@dimen/textSize20"/>
<TextView
android:layout_width="50dp"
android:layout_height="match_parent"
android:id="@+id/Collapser"
android:textSize="@dimen/textSize20"
android:textAllCaps="true"
android:text="+"
android:layout_gravity="center_vertical"
android:gravity="center"
android:layout_weight=".5"
android:textStyle="normal"/>
</LinearLayout>
ExpandableListAdapter
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private int[] headerIcons;
public ExpandableListAdapter(Context context,int[] headerIcons, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this.headerIcons = headerIcons;
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 String childText = (String) 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);
txtListChild.setText(childText);
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
@Override
public Object 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) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
ImageView headerImage = (ImageView)convertView.findViewById(R.id.navImage);
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setText(headerTitle);
TextView lvlPlusMinus=(TextView)convertView.findViewById(R.id.Collapser);
if(getChildrenCount(groupPosition)!=0)
{
lvlPlusMinus.setTypeface(null, Typeface.NORMAL);
lvlPlusMinus.setText("+");
if(isExpanded)
{
lvlPlusMinus.setTypeface(null, Typeface.NORMAL);
lvlPlusMinus.setText("-");
}
}
else
{
lvlPlusMinus.setText("");
}
headerImage.setImageResource(headerIcons[groupPosition]);
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
在导航栏中
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;
ExpandableListAdapter listAdapter;
ExpandableListView mDrawerListView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
private int lastExpandedPosition = -1;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
Map<String, String> params;
HashMap<String, String> userDetails;
public Fragment fragment = null;
String tag,URL ;
android.support.v4.app.FragmentManager fragmentManager;
FragmentTransaction transaction;
Handler handler;
Runnable runnable;
private final Handler mDrawerHandler = new Handler();
/**
* AppointmentRequest ♠♠
*/
ProgressDialog bar ;
public static final NavigationDrawerFragment NavUtils = new NavigationDrawerFragment();
public static NavigationDrawerFragment getInstance() {
return NavUtils;
}
public NavigationDrawerFragment() {
}
View contentView;
SessionManager session;
TextView doctorName;
ImageView docImage;
int[] headerIcons;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentManager = getFragmentManager();
transaction = fragmentManager.beginTransaction();
session = new SessionManager(getActivity());
// 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;
}
headerIcons = new int[]{
R.drawable.home,
R.drawable.profile,
R.drawable.logout
};
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) {
contentView = inflater.inflate(
R.layout.fragment_navigation_drawer_with_topheader, container, false);
mDrawerListView = (ExpandableListView) contentView.findViewById(R.id.expList);
doctorName = (TextView)contentView.findViewById(R.id.docName);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
selectItem(position);
}
});
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(getActivity(), headerIcons, listDataHeader, listDataChild);
mDrawerListView.setAdapter(listAdapter);
mDrawerListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
mDrawerListView.smoothScrollToPosition(groupPosition);
mDrawerListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
mDrawerListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v, final int groupPosition, long id) {
final String selected = (String) listDataHeader.get(groupPosition);
mDrawerListView.smoothScrollToPosition(groupPosition);
mDrawerHandler.removeCallbacksAndMessages(null);
mDrawerHandler.postDelayed(new Runnable() {
@Override
public void run() {
//Toast.makeText(getActivity(), selected, Toast.LENGTH_SHORT).show();
}
}, 250);
if (groupPosition == 0 ||)//close drawer if no child
mDrawerLayout.closeDrawers();
return false;
}
});
/**
* Expandable list child on click listener
*/
mDrawerListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, final int groupPosition, final int childPosition, long id) {
final String selected = (String) listAdapter.getChild(
groupPosition, childPosition);
mDrawerListView.smoothScrollToPosition(groupPosition);
mDrawerHandler.removeCallbacksAndMessages(null);
mDrawerHandler.postDelayed(new Runnable() {
@Override
public void run() {
// Toast.makeText(getActivity(), selected, Toast.LENGTH_SHORT).show();
}
}, 250);
mDrawerLayout.closeDrawers();
return true;
}
});
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return contentView;
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding Child in Parent
listDataHeader.add("Home");//0
listDataHeader.add("Profile");//1
listDataHeader.add("Sign out");//2
List<String> Profile = new ArrayList<String>();
Casefile.add("Child 1");
Casefile.add("Child 2");
listDataChild.put(listDataHeader.get(0), new ArrayList<String>());// Header, Child data
listDataChild.put(listDataHeader.get(1), Profile);
listDataChild.put(listDataHeader.get(2), new ArrayList<String>());//if no child
}
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 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);
actionBar.setHomeAsUpIndicator(R.drawable.dehaze);
// 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.dehaze, /* 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) {
outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE");
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) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
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);
}
/**
* Diplaying view for selected nav drawer list item
* */
private void displayView(final int position) {
// update the content by replacing fragments
switch (position) {
case 0:
mDrawerLayout.closeDrawers();
tag = "HomeFragment";
fragment = new HomeFragment();
break;
case 1:
mDrawerLayout.closeDrawers();
tag = "ProfileFragment";
fragment = new ProfileFragment();
break;
case 2:
mDrawerLayout.closeDrawers();
tag = "Signout";
fragment= null;
//Signout
break;
default:
break;
}
if (fragment != null) {
// update selected item and title, then close the drawer
mDrawerListView.setItemChecked(position, true);
mDrawerListView.setSelection(position);
mDrawerListView.smoothScrollToPosition(position);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.container, fragment, tag);
transaction.commit();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}