Khallad shahin
Khallad shahin

Reputation: 61

button to open another class for recycleView

This is my activity class and it has recycle view. right now i can click on the item in recycle view and it will open another class. I have a button when i click on it, i want it to open class. so basically repeat what happens when i press on the item but with a button. I tried using this int position3 = recyclerView.getChildLayoutPosition(v); to change the position of the item when i scroll so i can open the activity class depending on the item itself but i am getting this error.

android.widget.LinearLayout$LayoutParams cannot be cast to android.support.v7.widget.RecyclerView$LayoutParams`.

 FirebaseDatabase firebaseDatabaseInstance;
    private DatabaseReference booksInstance;
    AlbumDBHandler db;
    ArrayList<BookData> books = new ArrayList<>();
    private String TAG = mainActivityCarasoul.class.getSimpleName();
    private GalleryAdapter mAdapter;
    private RecyclerView recyclerView;
    private Button button;
    private int position2;

       @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_activity_carasoul);
             final CarouselLayoutManager layoutManager = new CarouselLayoutManager(CarouselLayoutManager.HORIZONTAL, true);
            layoutManager.setPostLayoutListener(new CarouselZoomPostLayoutListener2());

            recyclerView = (RecyclerView) findViewById(R.id.recycler_view_carasoul);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setHasFixedSize(true);

             button = (Button) findViewById(R.id.main_activity_button_carasoul);
             button.setOnClickListener(this);


            recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(this, recyclerView, new GalleryAdapter.ClickListener()
            {

                @Override
                public void onClick(View view, int position) {
                    position2 = recyclerView.getChildLayoutPosition(view);
                    mAdapter.notifyDataSetChanged();


                    Intent intent = new Intent(mainActivityCarasoul.this, PDFViewerActivity.class);
                    intent.putExtra(PDFViewerActivity.TAG, books.get(position));
                    intent.putExtra("from", "mainActivityCarasoul");
                    startActivity(intent);
                }
                @Override
                public void onLongClick(View view, int position) {
                }
            }));

            recyclerView.addOnScrollListener(new CenterScrollListener());

            db = new AlbumDBHandler(this);
            getData();
        }

private void getData(){
    firebaseDatabaseInstance = FirebaseDatabase.getInstance();

    // get reference to 'users' node
    booksInstance = firebaseDatabaseInstance.getReference("mo2lfat");

    books.clear();
    books.addAll(db.getAllBook());
    mAdapter = new GalleryAdapter(getApplicationContext(), books);
    recyclerView.setAdapter(mAdapter);

    if (books.isEmpty()) {

    }

    booksInstance.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            storeData(dataSnapshot);

        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w(TAG, "Failed to read value.", error.toException());
        }
    });
}

private void storeData(DataSnapshot snapshot) {
    books.clear();
    for (DataSnapshot alert: snapshot.getChildren()) {
        BookData book = new BookData(
                (String)alert.child("id").getValue(),
                (String)alert.child("book_name").getValue(),
                (String)alert.child("book_path").getValue(),
                (String)alert.child("book_path").getValue(),
                "",
                (String)alert.child("image_path").getValue(),
                (String)alert.child("image_path").getValue(),
                ""
        );
        db.insertBook(book);
    }
    books.addAll(db.getAllBook());
    mAdapter.notifyDataSetChanged();
}


        @Override
        public void onClick(View v) {

           // int position3 = recyclerView.getChildLayoutPosition(v);
             Intent intent = new Intent(mainActivityCarasoul.this, PDFViewerActivity.class);
            intent.putExtra(PDFViewerActivity.TAG, books.get(position2));
            intent.putExtra("from", "mainActivityCarasoul");
            startActivity(intent);
        }

This is my adapter class

Activity activity;
    ArrayList<BookData> images = new ArrayList<>();
    AlbumDBHandler db;
    private Context mContext;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public ImageView thumbnail;
        public TextView name;
        public Button button;

        public MyViewHolder(View view) {
            super(view);

            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
            name = (TextView) view.findViewById(R.id.textViewGallery);
        }
    }
    public GalleryAdapter(Context context, ArrayList<BookData> images) {
        mContext = context;
        this.images = images;
        this.db = new AlbumDBHandler(context);
    }

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

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {

        BookData image = images.get(position);

        if("".equals(images.get(position).getImageLocalPath())){

            Glide.with(mContext)
                    .load(images.get(position).getImagePath_2())
                    .thumbnail(0.5f)
                    .crossFade()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(holder.thumbnail);

            new ImageDownloaderTask(images.get(position)).execute(images.get(position).getImagePath_2());

        }else{
            Glide.with(mContext).load(new File(images.get(position).getImageLocalPath())).into(holder.thumbnail);
        }

        holder.name.setText(images.get(position).getName());
        }

    public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private GalleryAdapter.ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final GalleryAdapter.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) {

        }
    }

Upvotes: 0

Views: 443

Answers (4)

Dinith
Dinith

Reputation: 1

there was an easy peasy way to do that

itemView is my ViewHolder

 private Context context;


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

                    context = itemView.getContext();
                    Intent intent = new Intent(context, yourclss.class);
                    context.startActivity(intent);


                }
            });

Upvotes: 0

Shishupal Shakya
Shishupal Shakya

Reputation: 1672

Following line is throwing Exception you mentioned .

position2 = recyclerView.getChildLayoutPosition(view);

Here you don't need this line , you can use following line in place of above .

position2 = position ;

I have modified your code , One change I have mentioned above , there are two more change you need to do

1 . Comment notifyDataSetChanged() just below the getChildLayoutPosition(view)

2 . Set books before notifyDataSetChanged().

Here is modified code :

    FirebaseDatabase firebaseDatabaseInstance;
    private DatabaseReference booksInstance;
    AlbumDBHandler db;
    ArrayList<BookData> books = new ArrayList<>();
    private String TAG = mainActivityCarasoul.class.getSimpleName();
    private GalleryAdapter mAdapter;
    private RecyclerView recyclerView;
    private Button button;
    private int position2;

       @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_activity_carasoul);
             final CarouselLayoutManager layoutManager = new CarouselLayoutManager(CarouselLayoutManager.HORIZONTAL, true);
            layoutManager.setPostLayoutListener(new CarouselZoomPostLayoutListener2());

            recyclerView = (RecyclerView) findViewById(R.id.recycler_view_carasoul);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setHasFixedSize(true);

             button = (Button) findViewById(R.id.main_activity_button_carasoul);
             button.setOnClickListener(this);


            recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(this, recyclerView, new GalleryAdapter.ClickListener()
            {

                @Override
                public void onClick(View view, int position) {
                    //position2 = recyclerView.getChildLayoutPosition(view);
                    //mAdapter.notifyDataSetChanged();
                    position2 = position ;

                    Intent intent = new Intent(mainActivityCarasoul.this, PDFViewerActivity.class);
                    intent.putExtra(PDFViewerActivity.TAG, books.get(position));
                    intent.putExtra("from", "mainActivityCarasoul");
                    startActivity(intent);
                }
                @Override
                public void onLongClick(View view, int position) {
                }
            }));

            recyclerView.addOnScrollListener(new CenterScrollListener());

            db = new AlbumDBHandler(this);
            getData();
        }

private void getData(){
    firebaseDatabaseInstance = FirebaseDatabase.getInstance();

    // get reference to 'users' node
    booksInstance = firebaseDatabaseInstance.getReference("mo2lfat");

    books.clear();
    books.addAll(db.getAllBook());
    mAdapter = new GalleryAdapter(getApplicationContext(), books);
    recyclerView.setAdapter(mAdapter);

    if (books.isEmpty()) {

    }

    booksInstance.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            storeData(dataSnapshot);

        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w(TAG, "Failed to read value.", error.toException());
        }
    });
}

private void storeData(DataSnapshot snapshot) {
    books.clear();
    for (DataSnapshot alert: snapshot.getChildren()) {
        BookData book = new BookData(
                (String)alert.child("id").getValue(),
                (String)alert.child("book_name").getValue(),
                (String)alert.child("book_path").getValue(),
                (String)alert.child("book_path").getValue(),
                "",
                (String)alert.child("image_path").getValue(),
                (String)alert.child("image_path").getValue(),
                ""
        );
        db.insertBook(book);
    }
    books.addAll(db.getAllBook());
    mAdapter.setBooks(books);
    mAdapter.notifyDataSetChanged();
}


        @Override
        public void onClick(View v) {

           // int position3 = recyclerView.getChildLayoutPosition(v);
             Intent intent = new Intent(mainActivityCarasoul.this, PDFViewerActivity.class);
            intent.putExtra(PDFViewerActivity.TAG, books.get(position2));
            intent.putExtra("from", "mainActivityCarasoul");
            startActivity(intent);
        }

Now do following change inside your Adapter class .

1 . Add following method

public void setBooks(ArrayList<BookData> books){
  this.images = books ;

 }

Now Build your code and and check the issue .

Upvotes: 0

Ferdous Ahamed
Ferdous Ahamed

Reputation: 21756

# If your RecylcerView has items that contains Button and your want to change Activity by clicking on Button, then you can try this:

In your adapter onBindViewHolder(), set button onClick listener:

@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {

    BookData image = images.get(position);

    .............
    .................
    viewHolder.button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) 
        {
             // Do somethings
        }
    });

}

# If your MainActivityCarasoul has a Button and your want to change Activity by clicking on Button, then you can try this:

In your MainActivityCarasoul, do below changes:

...........
.................
private int mPosition = 0; // Initialize

@Override
protected void onCreate(Bundle savedInstanceState) {
    ........
    ................
    button = (Button) findViewById(R.id.main_activity_button_carasoul);

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) 
        {
            // Do somethings
            Intent intent = new Intent(mainActivityCarasoul.this, PDFViewerActivity.class);
            intent.putExtra(PDFViewerActivity.TAG, books.get(mPosition));
            intent.putExtra("from", "mainActivityCarasoul");
            startActivity(intent);
        }
    });

}

UPDATE:

To update the position try this:

recyclerView.addOnItemTouchListener(new 
GalleryAdapter.RecyclerTouchListener(this, recyclerView, new GalleryAdapter.ClickListener()
    {
         @Override
         public void onClick(View view, int position) {
            mPosition = position; // update

            ..............
            ....................
    }));

Hope this will help~

Upvotes: 1

Pranav Kumar H M
Pranav Kumar H M

Reputation: 987

There are two ways to do this.

One is set the onclicklistener to the recycler adapters recylers viewholder item view and execute your logic there. There you can access the position by viewholder.getadapterposition

Other method is if you are setting click listener to itemtouchlistener of recycler view then , the param which you get is the position. You again dont try to get the position by calling the getchildposition

This error comes because the items have parent has linearlayout so the view which is passed into getchilfpositiom have linearlayout params which is getting trouble casting to the recyclerview params which is the parent.

Better try to use the position which you get.

If you need to get the respective adapter item modify the adapter with a method that aacepts the position and returns the respective item.

Adapter.getItemAtPosition(position)

if you want to get respective item view. Recyclerview.getviewholder some method will be there.

Try those inbuilt functions of the recycler view rather using the view methods.

Upvotes: 0

Related Questions