我创建了一个带有RecyclerView的导航抽屉。我从YouTube那里学到了这一点。但是我无法实现" onNavigationDrawerItemSelected"它的方法。我想要做的是让用户能够点击列表中的项目,它将导航到活动而不是片段。
我是Android编程的新手,因此我很难理解代码。我已经在网上找到了教程,比如下面的链接,但它不会起作用。我花了很多时间试图解决这个问题,我得到的只是应用程序崩溃,不得不重新启动整个事情。如果有人能帮助我,那对我来说意味着很多。
How to navigate to different activities through the navigation drawer
OnItemClickListener Navigation Drawer
http://blog.evizija.si/android-layout/
以下是我为MainActivity,NavigationDrawer和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);
}
}
}
答案 0 :(得分:1)
在您的NavigationDrawerAdapter类中。
您需要实现GestureDetector方法以检测项目的位置。 你可以通过编写这段代码来实现这一点。
final GestureDetector mGestureDetector = new GestureDetector(YOUR_ACTIVITY_NAME.this, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
然后你可以实现addOnItemTouchListener,如:
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) {
}
});
现在您可以检查位置2,活动将开始而不是片段。 这段代码对我来说很完美..任何人都可以从中得到帮助。
答案 1 :(得分:0)
在适配器类中尝试:
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);
}
}
你必须有context
变量的引用,你可以拥有它,你可以在适配器类的构造函数中通过赋值来获取它。
希望这有帮助!