Navigation Drawer RecyclerView Items Click to an A

2019-05-26 06:03发布

I had created a Navigation Drawer with a RecyclerView inside of it. I had learned that from YouTube. However I had trouble implementing an "onNavigationDrawerItemSelected" method for it. What I want to do is for the user to be able to click on the items in the list and it will navigate them to an Activity instead of a Fragment.

I am new to android programming, hence I am bad in understanding the codes. I've looked everywhere on tutorials online such as the links below, but it wouldn't work. I've spent a lot of time trying to figure this out and all I get is the app crashing and had to restart the whole thing. It would mean alot to me if anyone can help me on this

How to navigate to different activities through the navigation drawer

OnItemClickListener Navigation Drawer

http://blog.evizija.si/android-layout/

Below are the codes that I have made for my MainActivity, NavigationDrawer and NavigationDrawerAdapter.

NavigationDrawerFragment:

public class NavigationDrawerFragment extends Fragment {

    private RecyclerView recyclerView;
    public static final String PREF_FILE_NAME = "testpref";
    public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawerLayout;
    private NavigationDrawerAdapter adapter;

    /*This is to tell the User that there is a navigation drawer*/
    private boolean mUserLearnedDrawer;
    private boolean mFromSavedInstanceState;
    private View containerView;

    public NavigationDrawerFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
        if (savedInstanceState != null) {
            mFromSavedInstanceState = true;
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
        recyclerView = (RecyclerView) layout.findViewById(R.id.navigation_drawer_list);
        adapter = new NavigationDrawerAdapter(getActivity(), getData());
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        return layout;
    }


    //Change the Drawables and Text Here for the NavigationDrawer List Items
    public static List<NavigationDrawerItems> getData() {
        List<NavigationDrawerItems> data = new ArrayList<>();
        int[] icons = {R.drawable.ic_account_circle_black_36dp, R.drawable.ic_home_black_36dp, R.drawable.ic_language_black_36dp, R.drawable.ic_redeem_black_36dp, R.drawable.ic_settings_black_36dp};
        String[] titles = {"Restaurants", "Categories", "Planner", "About Us", "Settings"};
        for (int i = 0; i < titles.length && i < icons.length; i++) {
            NavigationDrawerItems current = new NavigationDrawerItems();
            current.iconId = icons[i];
            current.title = titles[i];
            data.add(current);
        }
        return data;
    }


    public void setUp(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
        containerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;
        mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {


            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!mUserLearnedDrawer) {
                    mUserLearnedDrawer = true;
                    saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer + "");
                }
                getActivity().invalidateOptionsMenu();
            }


            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                getActivity().invalidateOptionsMenu();
            }
        };
        if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
            mDrawerLayout.openDrawer(containerView);

        }
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });
    }


    public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(preferenceName, preferenceValue);
        editor.apply();
    }


    public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(preferenceName, defaultValue);
    }

}

MainActivity:

public class MainActivity extends ActionBarActivity {

    private Toolbar toolbar;
    private NavigationDrawerFragment drawerFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_appbar);

        /*======= This three statement below is to add the customized ToolBar including the "private" statement above and the navigation drawer =======*/
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        drawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();


        /*======= The term "navigate" is taken from the menu_main.xml file. Rename them when necessary =======*/
        /*======= The startActivity statement enables the icon to be clicked and brings to another activity =======*/
        if (id == R.id.navigate) {
            startActivity(new Intent(this, SubActivity.class));
        }

        return super.onOptionsItemSelected(item);
    }
}

NavigationDrawerAdapter:

public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {

    private LayoutInflater inflater;
    List<NavigationDrawerItems> data = Collections.emptyList();

    public NavigationDrawerAdapter(Context context, List<NavigationDrawerItems> data) {
        inflater = LayoutInflater.from(context);
        this.data = data;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.fragment_navigation_drawer_row, parent, false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        NavigationDrawerItems current = data.get(position);
        holder.title.setText(current.title);
        holder.icon.setImageResource(current.iconId);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView title;
        ImageView icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.navigation_drawer_list_text);
            icon = (ImageView) itemView.findViewById(R.id.navigation_drawer_list_icon);
        }
    }
}

2条回答
看我几分像从前
2楼-- · 2019-05-26 06:26

In your NavigationDrawerAdapter class .

you need to implement GestureDetector method in order detect the position of the item . you can achieve this by writing this code .

        final GestureDetector mGestureDetector = new GestureDetector(YOUR_ACTIVITY_NAME.this, new GestureDetector.SimpleOnGestureListener() {

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

        });

Then you can implement a addOnItemTouchListener like:

mRecyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
                View child = recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());



                if(child!=null && mGestureDetector.onTouchEvent(motionEvent)){
                    Drawer.closeDrawers();
                    Toast.makeText(Scnd.this,"The Item Clicked is: "+recyclerView.getChildPosition(child),Toast.LENGTH_SHORT).show();


               int p=     recyclerView.getChildPosition(child);
                    if (p == 0){

                         Intent intent = new Intent(this, FirstActivity.class);

                         startActivity(intent);
                    } else if(p == 1){

                        Intent intent = new Intent(this,SecondActivity.class);

                        startActivity(intent);
                    }
                    else if(p == 2){

                      Intent mintent = new Intent(your_activity.this,to activity you want start.class);
                        startActivity(mintent);
                    }

                    child.setBackgroundColor(Color.WHITE);


                    return true;

                }

                return false;
            }

            @Override
            public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {

            }
        });

Now you can check on position 2 the activity will start instead of a fragment . this code is working for me perfectly .. any one may get help from this .

查看更多
我只想做你的唯一
3楼-- · 2019-05-26 06:32

Try this in your adapter class:

class MyViewHolder extends RecyclerView.ViewHolder {
      TextView title;
      ImageView icon;
      public MyViewHolder(View itemView) {
          super(itemView);
          itemView.setOnClickListener(new View.OnCLickListener() {
               @Override
               public void onClick(View v) {
                  Intent intent = new Intent(context, YourActivity.class);
                  context.startActivity(intent)
               }
          });                           
          itemView.findViewById(R.id.navigation_drawer_list_text);
          icon = (ImageView) itemView.findViewById(R.id.navigation_drawer_list_icon);
      }
}

you have to have a reference to the context variable, you can have it you can get it through assignment in the constructor of the adapter class.

Hope this helps!

查看更多
登录 后发表回答