0

my item_layout xml (see it like a template) contain a cardview with some texts and one button, when I run the application. the recyclerview shows two card views with different text (actor names, actors movies) all its ok, but the problem is when I made the button with an onclicklister method to show other activities. the result is when I click on button of the first card view and the button of the second cardview it shows the same result. what I want is when I click on button on the first cardview it shows Activity number 2, and when I click on the button on the second cardview must shows Activity number 3.

ps: I want different result when I click on button of each cardview

xml :

<RelativeLayout
    android:longClickable="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="5dp"
    android:paddingBottom="7dp">


    <ImageView

        android:id="@+id/profileImage"
        android:layout_width="70dp"
        android:layout_height="50dp"
        app:civ_border_color="#7f89e9"
        android:layout_marginLeft="5dp"
        android:background="@drawable/contact1"
        android:layout_alignTop="@+id/txtCelebName"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_marginTop="8dp"
        android:id="@+id/txtCelebName"
        android:textSize="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/profileImage"
        android:text="Large Text"
        android:layout_marginLeft="18dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_marginLeft="18dp"
        android:textSize="13dp"
        android:id="@+id/txtCelebMovie"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtCelebName"
        android:layout_toRightOf="@+id/profileImage"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:id="@+id/textView"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="27dp"
        android:layout_below="@+id/profileImage"
        android:text="heur/travaille : 5:00 pm - 8:00 am." />

    <TextView
        android:layout_marginLeft="10dp"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="emplacement de travaille : cité12  - cité42. "
        android:id="@+id/textView2"
        android:layout_below="@+id/textView3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_marginLeft="10dp"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="statut : disponible."
        android:id="@+id/textView3"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_marginLeft="5dp"

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="............"
        android:id="@+id/textView4"
        android:layout_below="@+id/profileImage" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="...................................."
        android:id="@+id/textView5"
        android:layout_alignLeft="@+id/textView4"
        android:layout_alignStart="@+id/textView4"
        android:layout_below="@+id/textView2"
        android:layout_marginBottom="5dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="go"
        android:id="@+id/buttonfordialog"
        android:layout_alignBottom="@+id/textView4"
        android:layout_toRightOf="@+id/textView3"
        android:layout_toEndOf="@+id/textView3" />


</RelativeLayout>

MainActivity java :

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;

    private ItemAdapter itemAdapter;

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


            View.OnClickListener btnListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                    startActivity(intent);


                }
            };






        final Toolbar toolbar = (Toolbar)findViewById(R.id.MyToolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapse_toolbar);
    collapsingToolbarLayout.setTitle("Alert ! ");


        ArrayList<Celebrity> itemList = new ArrayList<>();

        fillDummyData(itemList);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        itemAdapter = new ItemAdapter(itemList, btnListener);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(itemAdapter);
    }

    private void fillDummyData(ArrayList<Celebrity> celebList) {
        Celebrity celeb1 = new Celebrity();
        celeb1.setName("Johny.D");
        celeb1.setFamousMovie("Pirates  ");
        celeb1.setProfilePhotoLocation("@drawable/contact1");
        celebList.add(celeb1);

        Celebrity celeb2 = new Celebrity();
        celeb2.setName("Arnold");
        celeb2.setFamousMovie("The Terminator");
        celeb2.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTI3MDc4NzUyMV5BMl5BanBnXkFtZTcwMTQyMTc5MQ@@._V1._SY209_CR13,0,140,209_.jpg");
        celebList.add(celeb2);
    }
}

the Adapter :

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> {

private List<Celebrity> celebrityList;
private final View.OnClickListener btnListener;

public ItemAdapter(List<Celebrity> celebrityList, View.OnClickListener btnListener) {
    this.celebrityList = celebrityList;
    this.btnListener = btnListener;
}

@Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_layout, parent, false);

    return new ItemHolder(itemView, btnListener);
}

@Override
public void onBindViewHolder(ItemHolder holder, int position) {
    Celebrity item = celebrityList.get(position);
    holder.txtCelebName.setText(item.getName());
    holder.txtCelebMovie.setText(item.getFamousMovie());
}

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

    public class ItemHolder extends RecyclerView.ViewHolder {


        private  Button buttoncalling;
        public TextView txtCelebName, txtCelebMovie;
        public ImageView profileImage;

        public ItemHolder(View view, View.OnClickListener btnListener) {
        super(view);
            txtCelebName = (TextView) view.findViewById(R.id.txtCelebName);
            txtCelebMovie = (TextView) view.findViewById(R.id.txtCelebMovie);
            profileImage = (ImageView) view.findViewById(R.id.profileImage);
            buttoncalling  = (Button) view.findViewById(R.id.buttonfordialog);
            buttoncalling.setOnClickListener(btnListener);
        }
    }
}
C89-HD
  • 47
  • 9

3 Answers3

2

define OnClickListener inside onBindViewHolder();

      String [] activities={"FirstActivity","SecondActivity","ThirdActivity"};
      String packageNamePrefix="com.example."
    //String packageNamePrefix="YOUR_PACKAGE_NAME"


          @Override
          public void onBindViewHolder(ItemHolder holder,final int position) {
          Celebrity item = celebrityList.get(position);
          holder.txtCelebName.setText(item.getName());
          holder.txtCelebMovie.setText(item.getFamousMovie());

        holder.buttoncalling.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new 
                    Intent(MainActivity.this,Class.forName(packageNamePrefix+activities[position]));
            startActivity(intent);
        }
       });
      }

it will launch FirstActivity,SecondActivity,ThirdActivity respectively. I hope it will help.

Ajith Pandian
  • 1,332
  • 13
  • 21
  • with what i must replace "com.example" in String packageNamePrefix="com.example." – C89-HD Sep 20 '16 at 18:08
  • It is your package name you can find that on your AndroidManifest.xml with name of package="somthing.something.something". replace "com.package" with that. – Ajith Pandian Sep 20 '16 at 18:25
  • thanks , i found it , I want each button of cardview Open different Activity. give me a solution, please I need it. for example button of cardview number 2 open Activity 2 , and button of cardview number3 open Activity 3 . – C89-HD Sep 20 '16 at 18:35
  • Read this question and the answers you can find a solution. You just need to implement on click listener to the button in cardview inside your RecyclerviewAdapter. You can follow the given answers to get your thing done. – Ajith Pandian Sep 20 '16 at 18:41
  • but the onclick listener to the button in cardview inside my Recyclerviewadapter give the same result (All buttons of All card views open the same Activity). like I said in the question I need different result . – C89-HD Sep 20 '16 at 18:50
  • where you are implementing button's on click method? – Ajith Pandian Sep 20 '16 at 18:53
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/123813/discussion-between-c89-hd-and-ajith-pandian). – C89-HD Sep 20 '16 at 18:56
1

There are many ways to implement OnClickListener inside RecyclerView adapter.

  1. You can implement click listener inside onBindViewHolder() method like below

    holder.buttoncalling.setOnClickListener(new View.OnClickListener(){
       // perform click operation
    });
    
  2. You can also implement it inside you ItemHolder like this

    buttoncalling.setOnClickListener( new  View.OnClickListener(){
       // perform click operation    
    });
    

and use getAdapterPosition() whenever you need item clicked position as recommended in official docs.

  1. You can also make interface callbacks to your Activity and pass position along with it for refrence.
Rahul Khurana
  • 8,577
  • 7
  • 33
  • 60
  • how can i use getAdapterposition ? give me an example . – C89-HD Sep 19 '16 at 12:00
  • when you want position in **ItemHolder** to get which position was clicked to get data from **List** then you need **getAdapterPosition()** method – Rahul Khurana Sep 19 '16 at 12:05
  • i dont know how to use it ? – C89-HD Sep 20 '16 at 18:13
  • here is a nice tutorial [Android Working with Recycler View](http://www.androidhive.info/2016/01/android-working-with-recycler-view/) hope it helps. If it help you upto some extent please accept it as answer and upvote . Thanks – Rahul Khurana Sep 21 '16 at 03:40
0

You should use inline onclickListener like below;

YOURBUTTON.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       // your codes goes here...
   }
});
Phd. Burak Öztürk
  • 1,727
  • 19
  • 29