Reputation: 1005
I have a recylcerview in a navigation drawer and I wish to find what position was clicked by the user in the recyclerview in a different activity. The way I have written the code currently always return 0 as the position. Can anyone help me out. Thanks in advance!
Recyclerview in Navigation drawer code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final 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 NavigationDrawerFragmentAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView,new RecyclerViewClickListener() {
@Override
public void onClick(View view, int position) {
if (position == 0){
}
if (position == 27){
}
if (position == 28){
}
if (position == 29){
}
if (position ==30){
}
else{
test.getPositionClicked(position);
Intent i = new Intent(getActivity(), Test.class);
startActivity(i);
}
}
@Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
And My Activity code where I wish to find the position clicked:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Toast.makeText(Test.this, "Toast is working " + pos, Toast.LENGTH_SHORT).show();
if (pos == 1){
Toast.makeText(Test.this, "Accounting", Toast.LENGTH_SHORT).show();
}
}
public void getPositionClicked(int position) {
position = pos;
}
Thanks again!
Upvotes: 0
Views: 630
Reputation: 4651
You need to pass data in a bundle and add it to the intent of the new activity.
// onClick at recycler
Intent intent = new Intent();
intent.setClass(context, Other_Activity.class);
intent.putExtra("SOME_ID", position);
startActivity(intent);
//Second activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
int position = extras.getInt("SOME_ID");
}
Upvotes: 1
Reputation: 889
If I understood you correctly, you want to pass position to the activity, that you're starting. Then you can pass the value of position to the intent:
Intent i = new Intent(getActivity(), Test.class);
i.putExtra("position", position);
startActivity(i);
And then in your Test activity you retrieve the value:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Bundle extras = getIntent().getExtras();
if(extras != null) position = extras.getInt("position", 0);
}
Upvotes: 1