Hi I am trying to get a switch case statement to work for the navigation drawer for an android app. I have done to an onclick event to open the one activity, no matter what fragment you want to open. I know the structure of what I have to do (get the id of the selected item and open that fragment). Could someone just tell me where be best to input the piece of could and how to start if of.
Navigation Drawer Activity:
public class NavigationDrawerFragment extends Fragment implements BCRfmAdapter.ClickListener{
private RecyclerView recyclerView;
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
private ActionBarDrawerToggle mDrawerToogle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private BCRfmAdapter adapter;
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.drawerList);
adapter = new BCRfmAdapter(getActivity(), getData());
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position)
{
}
#Override
public void onLongClick(View view, int position)
{
}
}));
return layout;
}
public static List<Information> getData() {
//load only static data inside a drawer
List<Information> data = new ArrayList<>();
int[] icons = {R.drawable.ic_facebook, R.drawable.ic_facebook, R.drawable.ic_twitter, R.drawable.ic_action_about, R.drawable.ic_contact, R.drawable.ic_action_about};
String[] titles = {"Listen Live", "Facebook", "Twitter", "Google+", "About BCR FM", "Contact Us"};
for (int i = 0; i < 6; i++) {
Information current = new Information();
current.iconId = icons[i % icons.length];
current.title = titles[i % titles.length];
data.add(current);
}
return data;
//twitter://user?user_id=1721642934
//Started to add each item to the list rather than using an array..
// Add Drawer Item to dataList
/*data.add(new Information("Listen LIve", R.drawable.ic_launcher));
data.add(new Information("Facebook", R.drawable.ic_launcher));
data.add(new Information("Twitter", R.drawable.ic_launcher));
data.add(new Information("About BCRFm", R.drawable.ic_action_about));
data.add(new Information("Contact Us", R.drawable.ic_action_email));*/
}
//TODO switch case
#Override
public void itemClicked(View view, int position) {
startActivity(new Intent(getActivity(), devActivity.class));
}
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);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToogle = 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();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToogle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToogle.syncState();
}
});
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){
this.clickListener=clickListener;
gestureDetector=new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recyclerView.findChildViewUnder(e.getX(), e.getY());
if(child!=null && clickListener!=null)
{
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child=rv.findChildViewUnder(e.getX(), e.getY());
if(child!=null && clickListener!=null && gestureDetector.onTouchEvent(e))
{
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) { }
}
public static interface ClickListener{
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
}
And here is my DrawerAdapter code:
public class BCRfmAdapter extends RecyclerView.Adapter<BCRfmAdapter.MyViewHolder> {
List<Information> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
private ClickListener clickListener;
public BCRfmAdapter(Context context, List<Information> data){
this.context=context;
inflater=LayoutInflater.from(context);
this.data=data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information 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 implements View.OnClickListener {
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
title = (TextView) itemView.findViewById(R.id.listText);
icon = (ImageView) itemView.findViewById(R.id.listIcon);
}
#Override
public void onClick(View v) {
context.startActivity(new Intent(context, devActivity.class));
if(clickListener != null)
{
clickListener.itemClicked(v, getPosition());
}
}
}
public interface ClickListener{
public void itemClicked(View view, int position);
}
public void setClickListener(ClickListener clickListener){
this.clickListener=clickListener;
}
}
Related
I want to select an item by position in adapter programmatically
in my project i have an activity that get categories , now i want to select an item form this adapter automatic.
final result is :
after Home activity have been lunched when user clicks on the button and lunch the second activity that getting my categories from web service in the adapter and then select an item by position at adapter and run third activity that shown the content of the item.
Here is my codes
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
}
`
Update : AdapterCategory Codes
public class AdapterCategory extends RecyclerView.Adapter<AdapterCategory.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Category c = items.get(position);
holder.name.setText(Html.fromHtml(c.title));
holder.post_count.setText(c.post_count+"");
holder.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
Here is the Adapter (RVAdapter_Reminders.java)
static List<DatabaseModel> dbList;
static Context context;
DBHelper dbHelper;
private int position;
public RVAdapter_Reminders(Context context, List<DatabaseModel> dbList) {
this.dbList = new ArrayList<DatabaseModel>();
this.context = context;
this.dbList = dbList;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
#Override
public RVAdapter_Reminders.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rv_reminder_template, null);
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(final RVAdapter_Reminders.ViewHolder holder, final int position) {
holder.title.setText(dbList.get(position).getTitle());
holder.description.setText(dbList.get(position).getDescription());
holder.address.setText(dbList.get(position).getAddress());
holder.buttonViewOptions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//creating a popup menu
PopupMenu popup = new PopupMenu(context, holder.buttonViewOptions);
//inflating menu from xml
popup.inflate(R.menu.reminder_rv_menu);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
setPosition(holder.getAdapterPosition());
return false;
}
});
popup.show();
}
});
}
#Override
public void onViewRecycled(ViewHolder holder) {
holder.itemView.setOnClickListener(null);
super.onViewRecycled(holder);
}
#Override
public int getItemCount() {
return dbList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public TextView title, description, address, buttonViewOptions;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.task_title);
description = (TextView) itemView.findViewById(R.id.desc_title_text_tv);
address = (TextView) itemView.findViewById(R.id.address_title_text_tv);
buttonViewOptions = (TextView) itemView.findViewById(R.id.buttonViewOptions);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, R.id.menu_delete_option,
Menu.NONE, R.string.delete_menu_text);
}
}
Here is the Activity where the adapter is inflating data inside the RecyclerView
Reminders.java
FloatingActionButton fab;
DBHelper dbHelper;
List<DatabaseModel> dbList;
RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminders);
fab = (FloatingActionButton) findViewById(R.id.fab);
try {
getSupportActionBar().setTitle("Reminders");
} catch (Exception e) {
e.printStackTrace();
}
dbHelper = new DBHelper(this);
dbList = new ArrayList<DatabaseModel>();
dbList = dbHelper.getDataFromDB();
mRecyclerView = (RecyclerView) findViewById(R.id.rv_reminders);
mRecyclerView.setHasFixedSize(true);
// using a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
//specifying an adapter
mAdapter = new RVAdapter_Reminders(this, dbList);
mRecyclerView.setAdapter(mAdapter);
registerForContextMenu(mRecyclerView);
}
public void addReminder(View view) {
Intent intent = new Intent(Reminders.this, NewReminder.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Reminders.this, MainActivity.class);
startActivity(intent);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
int position = -1;
try{
position = ((RVAdapter_Reminders)mRecyclerView.getAdapter()).getPosition();
}catch (Exception e) {
Log.d(String.valueOf(this), e.getLocalizedMessage(), e);
return super.onContextItemSelected(item);
}
switch (item.getItemId()){
case R.id.menu_delete_option:
onReminderDelete(dbList.get(position).getTitle());
break;
}
return super.onContextItemSelected(item);
}
private void onReminderDelete(String title){
dbHelper.deleteARow(title);
mRecyclerView.setAdapter(mAdapter);
}
DeleteRow function in the DBHelper class:
public void deleteARow(String title) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(REMINDERS_TABLE, RemindersContract.TITLE + " = " + title, null);
Log.d(String.valueOf(this), title + " deleted");
db.close();
}
and finally, RemindersContract class:
public static final String TITLE = "title";
your mAdapter has still the values with deleted value. You must update your dbList to have current values.
private void onReminderDelete(String title){
dbHelper.deleteARow(title);
dbList.remove(/* value that you want remove*/);
mAdapter.notifyDataSetChanged();
}
I am able to change the color of the text and background of imageview of the row clicked of my recyclerview in my navigation drawer fragment.
But my problem is after clicking the 4th item,the 1st item also gets selected.Likewise after clicking my 5th item the 2nd item is selected.
Like this:
How do i solve this? So that only one item is selected at a time?
FragmentDrawer.java
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
int[] icons = {R.drawable.ic_home,
R.drawable.ic_upcoming,
R.drawable.ic_saved,
R.drawable.ic_wehappened,
R.drawable.ic_persons,
R.drawable.ic_music,
R.drawable.ic_parties,
R.drawable.ic_art, R.drawable.ic_network, R.drawable.ic_sports};
// preparing navigation drawer items
for (int i = 0; i < titles.length && i < icons.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
navItem.setIcon(icons[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();
//Sections
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(5, "Categories"));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
NavigationDrawerAdapter.selected_item = position;
recyclerView.getAdapter().notifyDataSetChanged();
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
SimpleSectionedRecyclerViewAdapter(getContext(), R.layout.section, R.id.section_text, adapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
//Apply this adapter to the RecyclerView
recyclerView.setAdapter(mSectionedAdapter);
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final 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);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
NavigationDrawerAdapter.java
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
List<NavDrawerItem> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public static int selected_item = 0;
public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.nav_drawer_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if(position == selected_item)
{
holder.title.setTextColor(Color.parseColor("#00aaff"));
holder.imgViewIcon.setBackgroundResource(R.drawable.ic_circle);
}
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
holder.imgViewIcon.setImageResource(current.getIcon());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
public ImageView imgViewIcon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
imgViewIcon = (ImageView) itemView.findViewById(R.id.item_icon);
}
}
}
EDIT: SimpleSectionedRecyclerViewAdapter.java
public class SimpleSectionedRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context mContext;
private static final int SECTION_TYPE = 0;
private boolean mValid = true;
private int mSectionResourceId;
private int mTextResourceId;
private LayoutInflater mLayoutInflater;
private RecyclerView.Adapter mBaseAdapter;
private SparseArray<Section> mSections = new SparseArray<Section>();
public SimpleSectionedRecyclerViewAdapter(Context context, int sectionResourceId, int textResourceId,
RecyclerView.Adapter baseAdapter) {
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSectionResourceId = sectionResourceId;
mTextResourceId = textResourceId;
mBaseAdapter = baseAdapter;
mContext = context;
mBaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
mValid = mBaseAdapter.getItemCount()>0;
notifyDataSetChanged();
}
#Override
public void onItemRangeChanged(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeChanged(positionStart, itemCount);
}
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeInserted(positionStart, itemCount);
}
#Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeRemoved(positionStart, itemCount);
}
});
}
public static class SectionViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public SectionViewHolder(View view,int mTextResourceid) {
super(view);
title = (TextView) view.findViewById(mTextResourceid);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int typeView) {
if (typeView == SECTION_TYPE) {
final View view = LayoutInflater.from(mContext).inflate(mSectionResourceId, parent, false);
return new SectionViewHolder(view,mTextResourceId);
}else{
return mBaseAdapter.onCreateViewHolder(parent, typeView -1);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder sectionViewHolder, int position) {
if (isSectionHeaderPosition(position)) {
((SectionViewHolder)sectionViewHolder).title.setText(mSections.get(position).title);
}else{
mBaseAdapter.onBindViewHolder(sectionViewHolder,sectionedPositionToPosition(position));
}
}
#Override
public int getItemViewType(int position) {
return isSectionHeaderPosition(position)
? SECTION_TYPE
: mBaseAdapter.getItemViewType(sectionedPositionToPosition(position)) +1 ;
}
public static class Section {
int firstPosition;
int sectionedPosition;
CharSequence title;
public Section(int firstPosition, CharSequence title) {
this.firstPosition = firstPosition;
this.title = title;
}
public CharSequence getTitle() {
return title;
}
}
public void setSections(Section[] sections) {
mSections.clear();
Arrays.sort(sections, new Comparator<Section>() {
#Override
public int compare(Section o, Section o1) {
return (o.firstPosition == o1.firstPosition)
? 0
: ((o.firstPosition < o1.firstPosition) ? -1 : 1);
}
});
int offset = 0; // offset positions for the headers we're adding
for (Section section : sections) {
section.sectionedPosition = section.firstPosition + offset;
mSections.append(section.sectionedPosition, section);
++offset;
}
notifyDataSetChanged();
}
public int positionToSectionedPosition(int position) {
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).firstPosition > position) {
break;
}
++offset;
}
return position + offset;
}
public int sectionedPositionToPosition(int sectionedPosition) {
if (isSectionHeaderPosition(sectionedPosition)) {
return RecyclerView.NO_POSITION;
}
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).sectionedPosition > sectionedPosition) {
break;
}
--offset;
}
return sectionedPosition + offset;
}
public boolean isSectionHeaderPosition(int position) {
return mSections.get(position) != null;
}
#Override
public long getItemId(int position) {
return isSectionHeaderPosition(position)
? Integer.MAX_VALUE - mSections.indexOfKey(position)
: mBaseAdapter.getItemId(sectionedPositionToPosition(position));
}
#Override
public int getItemCount() {
return (mValid ? mBaseAdapter.getItemCount() + mSections.size() : 0);
}
}
Change the onBindViewHolder method of your NavigationDrawerAdapter.java into this:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if(position == selected_item) {
holder.title.setTextColor(Color.parseColor("#00aaff"));
holder.imgViewIcon.setBackgroundResource(R.drawable.ic_circle);
} else {
holder.title.setTextColor(Color.parseColor("#00000")); //actually you should set to the normal text color
holder.imgViewIcon.setBackgroundResource(0);
}
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
holder.imgViewIcon.setImageResource(current.getIcon());
}
Simple and Best
Inside Adapter class
int row_index=0;
inside onBindViewHOlder
holder.titleLL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
row_index=position;
notifyDataSetChanged();
}
});
if (row_index==position) {
holder.title.setTextColor(Color.RED);
} else {
holder.title.setTextColor(Color.BLACK);
}
You can use class for Recycler view TouchListener
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private ClickListener clicklistener;
private GestureDetector gestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener){
this.clicklistener=clicklistener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child=rv.findChildViewUnder(e.getX(),e.getY());
RecyclerView.ViewHolder viewHolder=rv.findContainingViewHolder(child);
if(child!=null && clicklistener!=null && gestureDetector.onTouchEvent(e)){
clicklistener.onClick(child,rv.getChildAdapterPosition(child),viewHolder);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
Implement an Interface
public interface ClickListener{
public void onClick(View view, int position,RecyclerView.ViewHolder viewHolder);
public void onLongClick(View view, int position);
}
And in your Main Activity (Here I set Image resource You can set as You like ,Any thing)
Create an arraylist named "selected" as Integer and add following code as OnClickListener
recyclerViewSchedule.addOnItemTouchListener(new RecyclerTouchListener(this,
recyclerViewSchedule, new ClickListener() {
#Override
public void onClick(View view, final int position, RecyclerView.ViewHolder v) {
//Values are passing to activity & to fragment as well
if(!selected.contains(position))
{
selected.add(position);
((ScheduleAdapter.MyHolder) v).txtImage.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}else {
((ScheduleAdapter.MyHolder) v).txtImage.setBackgroundColor(getResources().getColor(R.color.colorTransparent));
selected.remove(new Integer(position));
}
Toast.makeText(ScheduleActivity.this, "Single Click on position :"+position,
Toast.LENGTH_SHORT).show();
}
Toast.makeText(ScheduleActivity.this, "Single Click on position :"+position,
Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(ScheduleActivity.this, "Long press on position :"+position,
Toast.LENGTH_LONG).show();
}
}));
The txtImage I specified here is from RecyclerAdapter,Replace it with Your View
Happy Coding :-)
most of the answers for such a question, are about to Override Onclick in onBindViewHolder or implementing an interface for clicking in recycler view. but as we all know, onBindViewHolder is called as your views are populated during scrolling. Thus, you will have numerous calls to setOnClickListener so it is not an efficient way and also implementing interface is not as easy as the answer I got.
here is how you can access selecting items in recycler view and change its background or do what ever you want when an item is selected .
in your ViewHolder constructor use setOnTouchListener for itemView (the argument of constructor) in this way
itemView.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (v.getTag() == null) {
v.setTag(true);
v.setBackgroundColor(Color.parseColor("#F31807"));
}
else {
v.setBackgroundColor(Color.TRANSPARENT);
v.setTag(null);
}
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
//default color
v.setBackgroundColor(Color.TRANSPARENT);
}
return true;
});
We use ACTION_UP for check if user pressed the item and after that we save a boolean in view's flag so that we can press every items how many times we want and see the color is changing. ACTION_MOVE if block is for prevent selecting items when scrolling the recycler view. if you see that selecting one item is affecting another items selection, you can use this answer:
issue : RecyclerView messed up data when scrolling
in the end if you are curious about why we return true in method see this video to understand.
tutorial on OnTouchListener And Motionevent
I have tried many different approaches but in the end, the solution that worked for me is
like first I was doing this
binding.download.setOnClickListener {
binding.download.visibility = View.GONE
binding.saved.visibility = View.VISIBLE
}
this was not working for me but after the below change
Instead of changing the color or visibility in onBindViewHolder, make a function in ViewHolder class and call it from onBindViewHolder
class ViewHolder(var binding: ImageRowBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(uri: Uri, mContext: Context) {
binding.download.setOnClickListener {
binding.download.visibility = View.GONE
binding.saved.visibility = View.VISIBLE
}
}
}
and calling this bind method from onBindViewHolder like this
holder.bind(items[position].uri, mContext)
works best for me
So i have a recyclerview on my fragment in a navigation drawer and it works jus fine.
However i would like to add a second recyclerview listing more items.
This is achievable but the hard part is making the whole layout scroll together.
I have google it up an havent found anything helpful.I thought maybe one of you might have a work around.
Is this possible?
FragmentDrawer.java
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
int[] icons = {R.drawable.home, R.drawable.ic_upcoming, R.drawable.ic_eventsaved, R.drawable.ic_wehappened, R.drawable.ic_persons};
// preparing navigation drawer items
for (int i = 0; i < titles.length && i < icons.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
navItem.setIcon(icons[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final 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);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
NavigationDrawerAdapter.java
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
List<NavDrawerItem> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.nav_drawer_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
holder.imgViewIcon.setImageResource(current.getIcon());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
public ImageView imgViewIcon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
imgViewIcon = (ImageView) itemView.findViewById(R.id.item_icon);
}
}
}
strings.xml
<resources>
<string name="nav_item_home">Home</string>
<string name="nav_item_friends">Upcoming</string>
<string name="nav_item_notifications">Saved</string>
<string name="nav_item_main">weHappened</string>
<string name="nav_item_planners">Event planners</string>
<!-- navigation drawer item labels -->
<string-array name="nav_drawer_labels">
<item>#string/nav_item_home</item>
<item>#string/nav_item_friends</item>
<item>#string/nav_item_notifications</item>
<item>#string/nav_item_main</item>
<item>#string/nav_item_planners</item>
</string-array>
<string name="title_messages">Events saved</string>
<string name="title_friends">Upcoming events</string>
<string name="title_home">Home</string>
<string name="title_happened">Events weHappened</string>
<string name="title_planners">Event planners</string>
</resources>
Use a single RecyclerView if you like to list more items in the same list. There is no point in using 2 different RecyclerViews and you can't make them scroll together if these are one below the other.
If you want to add more items to the list dynamically, build an "update" method in your Adapter and call that method when you'd like to add more items and call notifyItemRangeChanged() (or the most appropriate methods given the the RecyclerView.Adapter class)
EDIT:
Assuming you have a RecyclerView set and you know how to initialize and set it up with a basic LinearLayoutManager, I would like to focus only on the adapter.
So if you'd like to separate 2 categories like "Main options" and "Other options" you may want to consider implementing your adapter for 2 view types. Here is a short code snippet on how to achieve that but this highlights only the idea of how to use multiple view types. You may want to modify it to your needs:
public class DrawerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int VIEW_TYPE_HEADER = 0;
private static final int VIEW_TYPE_REGULAR_ITEM = 1;
private LayoutInflater mInflater;
private List<Object> mItems;
public DrawerAdapter(Context context) {
mInflater = LayoutInflater.from(context);
mItems = new ArrayList<>();
mItems.add("Main options");
mItems.add(new Item("Option1", R.drawable.icons_for_option_1))
mItems.add(new Item("Option2", R.drawable.icons_for_option_2))
mItems.add(new Item("Option2", R.drawable.icons_for_option_2))
mItems.add(new Item("Option3", R.drawable.icons_for_option_3))
mItems.add("Secondary options")
mItems.add(new Item("Option4", R.drawable.icons_for_option_4))
// And so on...whatever the logic is.
}
#Override
public int getItemCount() {
return mItems.size();
}
#Override
public int getItemViewType(int position) {
if (position == 0 || position == 5) { // Assuming that the topmost item and the 5th item are the section headers. This if statement can be simplified too.
return VIEW_TYPE_HEADER;
} else {
return VIEW_TYPE_REGULAR_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_HEADER) {
return new HeaderViewHolder(mInflater.inflate(R.layout.list_item_header, parent, false));
} else {
return new RegularItemViewHolder(mInflater.inflate(R.layout.list_item_regular, parent, false));
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof HeaderViewHolder) {
((HeaderViewHolder) holder).setup(mItems.get(position));
} else if (holder instanceof RegularItemViewHolder) {
((RegularItemViewHolder) holder).setup(mItems.get(position));
}
}
private static class RegularItemViewHolder extends RecyclerView.ViewHolder {
private RegularItemViewHolder(View convertView) {
super(convertView);
// Initialize your views here. Let's say you will have a TextView and an icon here or whatever else.
}
public void setup(Item item) {
// Update your views here, etc.
}
}
private static class HeaderViewHolder extends RecyclerView.ViewHolder {
TextView titleTextView;
private HeaderViewHolder(View convertView) {
super(convertView);
titleTextView = convertView.findViewById(R.id.section_header);
}
public void setup(String sectionHeaderTitle) {
yourTextView.setText(title);
}
}
}
And this would be it. Sorry for eventual mistakes, I didn't test the code.
Cheers!
I have a recycler view that has many items that I want to intent from every item to specific activities. I tried many ways but all fail to intent to the activities.
This is the adapter:
public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.ViewHolder> {
private ArrayList<String> itemsData;
public ItemsAdapter(ArrayList<String> itemsData) {
this.itemsData = itemsData;
}
#Override
public ItemsAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent,
int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item, null);
final ViewHolder viewHolder = new ViewHolder(itemLayoutView);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String word = viewHolder.txtViewTitle.getText().toString();
Toast.makeText(parent.getContext(),word,Toast.LENGTH_LONG).show();
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
viewHolder.txtViewTitle.setText(itemsData.get(position));
viewHolder.imgViewIcon.setImageResource(R.drawable.imsge_profile);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtViewTitle;
public ImageView imgViewIcon;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
}
}
#Override
public int getItemCount() {
return itemsData.size();
}
}
This is main_activity:
public class MainActivity extends ActionBarActivity {
Toolbar tBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tBar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(tBar);
getSupportActionBar().setTitle("AdroidCode Recycler View");
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
ArrayList<String> listItems = new ArrayList<String>();
listItems.add("Tom");
listItems.add("Hamdy");
listItems.add("John");
listItems.add("Hasna");
listItems.add("Fadi");
listItems.add("Samer");
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ItemsAdapter mAdapter = new ItemsAdapter(listItems);
recyclerView.setAdapter(mAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
}
i tried this instead of the Toast but dosent work
#Override
public void onClick(View v) {
final Intent intent;
switch (getPostion()){
case 0:
intent = new Intent(context, FirstActivity.class);
break;
case 1:
intent = new Intent(context, SecondActivity.class);
break;
...
default:
intent = new Intent(context, DefaultActivity.class);
break;
}
context.startActivity(intent);
}
new adapter
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
public static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView personName;
TextView personAge;
ImageView personPhoto;
public PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
personName = (TextView)itemView.findViewById(R.id.person_name);
personAge = (TextView)itemView.findViewById(R.id.person_age);
personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
recyclerview.addOnItemTouchListener(new RecyclerItemClickListener(
context, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// TODO Auto-generated method stub
final Intent intent;
switch (position) {
case 0:
intent = new Intent(context, secoundActivity.class);
break;
}
}
));
}}
}
List<Person> persons;
RVAdapter(List<Person> persons){
this.persons = persons;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
personViewHolder.personName.setText(persons.get(i).name);
personViewHolder.personAge.setText(persons.get(i).age);
personViewHolder.personPhoto.setImageResource(persons.get(i).photoId);
}
#Override
public int getItemCount() {
return persons.size();
}
}
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
// do whatever
}
})
);
I think you need to add click listener when you intialilize recycler view.Try these
public class RecyclerItemClickListener implements
RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context,
OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null
&& mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView,
view.getChildPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
}
You can not direct use onclick. I have found a solution and it's works for me. Try it. I hope it will helps you.
Step 1: Fist add this RecyclerItemClickListener class to your package.
public class RecyclerItemClickListener implements
RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context,
OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null
&& mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView,
view.getChildPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
}
Step 2: Now use onclick method. this gives you position of item clicked. Once you get position than you can use it as per your requirement.
recyclerview.addOnItemTouchListener(new RecyclerItemClickListener(
context, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, position + "",
Toast.LENGTH_SHORT).show();
final Intent intent;
switch (position) {
case 0:
Toast.makeText(context, "case 0",
Toast.LENGTH_SHORT).show();
intent = new Intent(context,FirstActivity.class);
break;
case 1:
Toast.makeText(context, "case 1",
Toast.LENGTH_SHORT).show();
intent = new Intent(context,SecondActivity.class);
break;
default:
intent = new Intent(context,DefaultActivity.class);
break;
}
}));