简体   繁体   English

在导航抽屉项目上单击,导航抽屉中的新列表视图

[英]On navigation drawer item click, new list view in navigation drawer

I am trying to get the following functionality in navigation drawer but i am not able to break it. 我试图在导航抽屉中获得以下功能,但我无法打破它。

scenario:- 场景: -

I am having a Navigation Drawer. 我有一个导航抽屉。 On clicking any item in the navigation drawer I need a list view to open with multiple item in it, which could be further selected for some kind of functionality. 单击导航抽屉中的任何项目时,我需要一个列表视图,其中包含多个项目,可以进一步选择某种功能。 I am also attaching the Image which will Define my need in appropriate manner. 我还附上了Image,它将以适当的方式定义我的需求。 Please have a kind reference of the Image to get What I basically and actually need. 请有一个图像的参考,以获得我基本上和实际需要的东西。 导航抽屉有多个列表

Any help would be appreciated..! 任何帮助,将不胜感激..!

As i Have see your image what i understand is that, from your drawer click you want another list appear it's right side . 正如我已经看到你的形象我所理解的是, 从你的抽屉点击你想要另一个列表出现它是正确的。 am I correct ? 我对么 ? If I correct then it is not possible using ExpandableListView becuase ExpandableListView will generate the item below the clicked item. 如果我更正 ,则无法使用ExpandableListView,因为ExpandableListView将生成所单击项目下方的项目。

So one solution is that You can take two ListView. 所以一个解决方案就是你可以拿两个ListView。

First ListView inside drawer and Second one on your main content and create custom adapter for both ListView. 第一个ListView内部抽屉第二个主内容,并为ListView创建自定义适配器。

Now when user click drawer list item, identify which option is clicked like City, MyNews or whatever. 现在, 当用户单击抽屉列表项时,标识单击哪个选项,如City,MyNews或其他任何内容。

After identifying the click you can fill your adapter for second ListView according to which option is clickd by user. 识别出点击后,您可以根据用户点击的选项为第二个ListView填充适配器。 and apply that adapter to second ListView and notify it. 并将该适配器应用于第二个ListView并通知它。

So when user click on another item from drawer the same thing going to happen. 因此,当用户点击抽屉中的另一个项目时,同样的事情将会发生。 But the data for second ListView are going to change. 但第二个ListView的数据将会发生变化。

I hope you understand what I am saying and It helps you. 我希望你明白我在说什么,它会帮助你。

[update] [更新]

Ok so your xml shuold look like this. 好的,你的xml shuold看起来像这样。

Note: I am just writing a skeleton for this. 注意:我只是为此写一个骨架。

<!-- The main content view -->
<FrameLayout android:id="@+id/content_frame" />

<!-- The navigation drawer -->
<LinearLayout
    android:layout_gravity="start"
    android:orientation="horizontal">
    <ListView
        android:layout_weight="1"
        android:id="@+id/list1">
    </ListView>

    <ListView
        android:layout_weight="1"
        android:id="@+id/list2">
    </ListView>
</LinearLayout>

Now On Your java side. 现在在你的Java方面。 consider both listview are referenced as list1 and list2 , and you have created two adapter adapter1 and adapter2 . 考虑将listview引用为list1list2 ,并创建了两个适配器adapter1adapter2

Make Item click for list1 and apply the logic like below ... 单击列表1的项目,然后应用如下逻辑...

list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {

        // now here you can get which option is clicked from list1.
        // using position and 
        int your_type = pos;

        adapter2.filderDataAccordingToType(your_type);
        // create the above method in your second adapter and pass your type like MyNews, City or any other.
        // and apply the logic of filtering by passing type to your method
        // your_type could be any data type i have take the integer.
        // and after filtering data you can notify your adapter.
        // so when the data of adpater gets changed your secondlistview get refreshed.
    }
});

that's it. 而已。 I hope it helps you. 我希望它对你有所帮助。

You can use the Android Developers tutorial on creating a navigation drawer , but instead of using ListView, you go for an ExpandableListView . 您可以使用Android Developers教程创建导航抽屉 ,但不是使用ListView,而是使用ExpandableListView

For example, in that tutorial, you can see that in the first block of code they are using a ListView . 例如,在该教程中,您可以看到在第一个代码块中,它们使用的是ListView Instead of that, change it to something like this: 而不是那样,把它改成这样的东西:

<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">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ExpandableListView android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"/>
</android.support.v4.widget.DrawerLayout>

How to implement a ExpandableListView adapter is well explained in this tutorial available at Android Hive. Android Hive中提供的教程中详细解释了如何实现ExpandableListView适配器。 I'm not pasting their code here because it's a long tutorial. 我没有粘贴他们的代码,因为这是一个很长的教程。 Comment bellow if you have any questions. 如果您有任何疑问,请发表评论。

here is my code. 这是我的代码。

  • i am using recycler view for child item. 我正在使用儿童用品的回收视图。
  • it is expanding down words. 它正在扩大话语。
  • i am using 2 library. 我正在使用2个库。

    compile 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.7.1' compile 'com.wnafee:vector-compat:1.0.5' 编译'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.7.1'compile'c​​om.wnafee:vector-compat:1.0.5'

here is Navigation Drawer Fragment 这是导航抽屉碎片

public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {


private static final String SAVED_STATE_EXPANDABLE_ITEM_MANAGER = "RecyclerViewExpandableItemManager";

/**
 * 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 mActionBarDrawerToggle;

private DrawerLayout mDrawerLayout;
private RecyclerView mDrawerList;
private View mFragmentContainerView;

private int mCurrentSelectedPosition = -1;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;

private Subscription subscription;

@Inject CategoryService categoryService;

private MyExpandableItemAdapter expandableItemAdapter;
private RecyclerView.Adapter wrappedAdapter;
private RecyclerViewExpandableItemManager expandableItemManager;
private LinearLayoutManager linearLayoutManager;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    DelhiShopApplication.component().inject(this);

    // 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;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
    mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mDrawerList.setLayoutManager(layoutManager);
    mDrawerList.setHasFixedSize(true);

    if (mCurrentSelectedPosition != -1) {
        selectItem(mCurrentSelectedPosition);
    }
    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    final Parcelable eimSavedState = (savedInstanceState != null) ? savedInstanceState.getParcelable(SAVED_STATE_EXPANDABLE_ITEM_MANAGER) : null;
    expandableItemManager = new RecyclerViewExpandableItemManager(eimSavedState);


}

private void setRecyclerView(Category category) {
    linearLayoutManager = new LinearLayoutManager(getActivity());

    final MyExpandableItemAdapter myItemAdapter = new MyExpandableItemAdapter(category);
    wrappedAdapter = expandableItemManager.createWrappedAdapter(myItemAdapter);


    final GeneralItemAnimator animator = new RefactoredDefaultItemAnimator();

    // Change animations are enabled by default since support-v7-recyclerview v22.
    // Need to disable them when using animation indicator.
    animator.setSupportsChangeAnimations(false);

    mDrawerList.setLayoutManager(linearLayoutManager);
    mDrawerList.setAdapter(wrappedAdapter);  // requires *wrapped* adapter
    mDrawerList.setItemAnimator(animator);
    mDrawerList.setHasFixedSize(false);

    // additional decorations
    //noinspection StatementWithEmptyBody

// if (supportsViewElevation()) { // // Lollipop or later has native drop shadow feature. // if(supportsViewElevation()){// // Lollipop或更高版本具有原生投影功能。 ItemShadowDecorator is not required. ItemShadowDecorator不是必需的。 // } else { // mDrawerList.addItemDecoration(new ItemShadowDecorator((NinePatchDrawable) getResources().getDrawable(R.drawable // .material_shadow_z1))); //} else {// mDrawerList.addItemDecoration(new ItemShadowDecorator((NinePatchDrawable)getResources()。getDrawable(R.drawable // .material_shadow_z1))); // } //}

    expandableItemManager.attachRecyclerView(mDrawerList);
}

private boolean supportsViewElevation() {
    return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
}

public boolean isDrawerOpen() {
    return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}

public ActionBarDrawerToggle getActionBarDrawerToggle() {
    return mActionBarDrawerToggle;
}

public DrawerLayout getDrawerLayout() {
    return mDrawerLayout;
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    selectItem(position);
}

/**
 * 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.
 * @param toolbar      The Toolbar of the activity.
 */
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
    mFragmentContainerView = (View) getActivity().findViewById(fragmentId).getParent();
    mDrawerLayout = drawerLayout;

    mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.myPrimaryDarkColor));

    mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string
            .drawer_open, R.string.drawer_close) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            if (!isAdded()) {
                return;
            }

            getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            if (!isAdded()) {
                return;
            }
            if (!mUserLearnedDrawer) {
                mUserLearnedDrawer = true;
                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(getActivity());
                sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
            }
            getActivity().invalidateOptionsMenu(); // 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() {
            mActionBarDrawerToggle.syncState();
        }
    });

    mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}

private void selectItem(int position) {
    mCurrentSelectedPosition = position;
    if (mDrawerLayout != null) {
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }
    if (mCallbacks != null) {
        mCallbacks.onNavigationDrawerItemSelected(position);
    }
    ((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}

public void openDrawer() {
    mDrawerLayout.openDrawer(mFragmentContainerView);
}

public void closeDrawer() {
    mDrawerLayout.closeDrawer(mFragmentContainerView);
}

@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);
    if (expandableItemManager != null) {
        outState.putParcelable(
                SAVED_STATE_EXPANDABLE_ITEM_MANAGER,
                expandableItemManager.getSavedState());
    }
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Forward the new configuration the drawer toggle component.
    mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}

public void setUserData(String user, String email, Bitmap avatar) {
    ((TextView) mFragmentContainerView.findViewById(R.id.txtUserEmail)).setText(email);
    ((TextView) mFragmentContainerView.findViewById(R.id.txtUsername)).setText(user);
}

public View getGoogleDrawer() {
    return mFragmentContainerView.findViewById(R.id.googleDrawer);
}

@Override
public void onResume() {
    super.onResume();
    subscription = categoryService.getCategories()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<Category>() {
                @Override
                public void call(Category category) {
                    // sadfksdjf
                    expandableItemAdapter = new MyExpandableItemAdapter(category);
                    mDrawerList.setAdapter(expandableItemAdapter);
                    setRecyclerView(category);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    // slkdfj
                }

            });
}


@Override
public void onPause() {
    subscription.unsubscribe();
    super.onPause();
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    if (expandableItemManager != null) {
        expandableItemManager.release();
        expandableItemManager = null;
    }
}

here is My Expandable Item Adapter 这是我的可扩展项目适配器

public class MyExpandableItemAdapter
    extends AbstractExpandableItemAdapter<MyExpandableItemAdapter.MyGroupViewHolder, MyExpandableItemAdapter.MyChildViewHolder> {
private static final String TAG = "MyExpandableItemAdapter";

private Category category;

public static abstract class MyBaseViewHolder extends AbstractExpandableItemViewHolder {
    public ViewGroup mContainer;
    public View mDragHandle;
    public TextView mTextView;

    public MyBaseViewHolder(View v) {
        super(v);
        mContainer = (ViewGroup) v.findViewById(R.id.container);
        mDragHandle = v.findViewById(R.id.drag_handle);
        mTextView = (TextView) v.findViewById(android.R.id.text1);

        // hide the drag handle
        mDragHandle.setVisibility(View.GONE);
    }
}

public static class MyGroupViewHolder extends MyBaseViewHolder {
    public MorphButtonCompat mMorphButton;

    public MyGroupViewHolder(View v) {
        super(v);
        mMorphButton = new MorphButtonCompat(v.findViewById(R.id.indicator));
    }
}

public static class MyChildViewHolder extends MyBaseViewHolder {
    public MyChildViewHolder(View v) {
        super(v);
    }
}

public MyExpandableItemAdapter(Category dataProvider) {
    category = dataProvider;

    // ExpandableItemAdapter requires stable ID, and also
    // have to implement the getGroupItemId()/getChildItemId() methods appropriately.
    setHasStableIds(true);
}

@Override
public int getGroupCount() {
    return category.getSubCategorySize();
}

@Override
public int getChildCount(int groupPosition) {
    return getGroupCategoryAtPosition(groupPosition).getSubCategorySize();
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return groupPosition * 100 + childPosition;
}

@Override
public int getGroupItemViewType(int groupPosition) {
    return 0;
}

@Override
public int getChildItemViewType(int groupPosition, int childPosition) {
    return 0;
}

@Override
public MyGroupViewHolder onCreateGroupViewHolder(ViewGroup parent, int viewType) {
    final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    final View v = inflater.inflate(R.layout.list_group_item, parent, false);
    return new MyGroupViewHolder(v);
}

@Override
public MyChildViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
    final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    final View v = inflater.inflate(R.layout.list_item, parent, false);
    return new MyChildViewHolder(v);
}

@Override
public void onBindGroupViewHolder(MyGroupViewHolder holder, int groupPosition, int viewType) {
    // child item

    final Category groupItem = getGroupCategoryAtPosition(groupPosition);

    // set text
    holder.mTextView.setText(groupItem.getCategoryName());

    // mark as clickable
    holder.itemView.setClickable(true);

    // set background resource (target view ID: container)
    final int expandState = holder.getExpandStateFlags();

    if ((expandState & RecyclerViewExpandableItemManager.STATE_FLAG_IS_UPDATED) != 0) {
        int bgResId;
        MorphButton.MorphState indicatorState;

        if ((expandState & RecyclerViewExpandableItemManager.STATE_FLAG_IS_EXPANDED) != 0) {
            bgResId = R.drawable.bg_group_item_expanded_state;
            indicatorState = MorphButton.MorphState.END;
        } else {
            bgResId = R.drawable.bg_group_item_normal_state;
            indicatorState = MorphButton.MorphState.START;
        }

        holder.mContainer.setBackgroundResource(bgResId);

        if (holder.mMorphButton.getState() != indicatorState) {
            holder.mMorphButton.setState(indicatorState, true);
        }
    }
}

@Override
public void onBindChildViewHolder(MyChildViewHolder holder, int groupPosition, int childPosition, int viewType) {
    // group item
    final Category childCategory = getChildCategory(groupPosition, childPosition);
    // set text
    holder.mTextView.setText(childCategory.getCategoryName());

    // set background resource (target view ID: container)
    int bgResId;
    bgResId = R.drawable.bg_item_normal_state;
    holder.mContainer.setBackgroundResource(bgResId);
}


@Override
public boolean onCheckCanExpandOrCollapseGroup(MyGroupViewHolder holder, int groupPosition, int x, int y, boolean expand) {

    Category groupCategory = getGroupCategoryAtPosition(groupPosition);

    if (groupCategory.getSubCategorySize() == 0) {
        return false;
    }

    // check is enabled
    if (!(holder.itemView.isEnabled() && holder.itemView.isClickable())) {
        return false;
    }

    final View containerView = holder.mContainer;
    final View dragHandleView = holder.mDragHandle;

    final int offsetX = containerView.getLeft() + (int) (ViewCompat.getTranslationX(containerView) + 0.5f);
    final int offsetY = containerView.getTop() + (int) (ViewCompat.getTranslationY(containerView) + 0.5f);

    return !hitTest(dragHandleView, x - offsetX, y - offsetY);
}

private Category getGroupCategoryAtPosition(int groupPosition) {
    return category.getSubCategory().get(groupPosition);
}

private Category getChildCategory(int groupPosition, int childPosition) {
    return getGroupCategoryAtPosition(groupPosition).getSubCategory().get(childPosition);
}


public static boolean hitTest(View v, int x, int y) {
    final int tx = (int) (ViewCompat.getTranslationX(v) + 0.5f);
    final int ty = (int) (ViewCompat.getTranslationY(v) + 0.5f);
    final int left = v.getLeft() + tx;
    final int right = v.getRight() + tx;
    final int top = v.getTop() + ty;
    final int bottom = v.getBottom() + ty;

    return (x >= left) && (x <= right) && (y >= top) && (y <= bottom);
}
}

here is my list_group_item.xml 这是我的list_group_item.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="@style/commonListItemStyle"
android:layout_width="match_parent"
android:layout_height="96dp"
android:layout_marginTop="8dp"
android:background="#ffffff">

<RelativeLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    tools:ignore="UselessParent">

    <View
        android:id="@+id/drag_handle"
        android:layout_width="32dp"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="#20000000"
        tools:ignore="RtlHardcoded" />

    <TextView
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_toRightOf="@id/drag_handle"
        android:gravity="center" />
</RelativeLayout>

</FrameLayout>

list_item.xml list_item.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="@style/commonListItemStyle"
android:layout_width="match_parent"
android:layout_height="64dp"
android:background="@drawable/bg_swipe_item_neutral">

<RelativeLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    tools:ignore="UselessParent">

    <View
        android:id="@+id/drag_handle"
        android:layout_width="32dp"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="#20000000" />

    <TextView
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_toRightOf="@id/drag_handle"
        android:gravity="center"
        tools:ignore="RtlHardcoded" />
</RelativeLayout>

</FrameLayout>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM