Android:Intent from Recycler View to Activity

2019-06-12 10:21发布

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();
}

}

3条回答
Emotional °昔
2楼-- · 2019-06-12 10:39
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

查看更多
来,给爷笑一个
3楼-- · 2019-06-12 10:50

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

查看更多
男人必须洒脱
4楼-- · 2019-06-12 10:56

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) {
	}
}

查看更多
登录 后发表回答