Android Spinner Inside RecyclerView Get Current View When Selected

12,886

You can set an OnClickListener on mGameSpinner in your onBindViewHolder().

onBindViewHolder(final PopularAdapter.MyViewHolder holder, final int position)

You can then store/use the position parameter as it will be the index into your gameArray for that particular spinner. You can then use that index to grab the spinner's currently selected value and do whatever you need to do with it.

Share:
12,886
jdoyle1331
Author by

jdoyle1331

Updated on June 05, 2022

Comments

  • jdoyle1331
    jdoyle1331 almost 2 years

    I have a RecyclerView implementing a LinearLayout of CardViews through an adapter. Inside each CardView, I have a spinner. What I need to do is get the CardViews position when a spinner is selected. Ex.. if I have 10 CardViews in a list on the screen with a spinner in each, and a select a value from the spinner in the 5th item, I need to get that 5th position as well as the selected value.

    I'm able to get the selected value just fine. The issue is with getting the CardViews position. The CardViews are being generated from an ArrayList.

    I will include my code below along with an image of the desired results. Any help is greatly appreciated!!

    enter image description here

    RecyclerView Adapter

    public class PopularAdapter extends RecyclerView.Adapter<PopularAdapter.MyViewHolder> {
    
        PopularFragment mPopularFragment;
        private Context mContext;
        private ArrayList<GameData> gameDataArr = new ArrayList<GameData>();
        private String userId;
    
        public PopularAdapter(Context context, ArrayList<GameData> gameDataArr, PopularFragment mPopularFragment, String userId) {
            mContext = context;
            this.gameDataArr = gameDataArr;
            this.mPopularFragment = mPopularFragment;
            this.userId = userId;
        }
    
        public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            public TextView title;
            public ImageView thumbnail;
            private CardView mCardView;
            PopularFragment mPopularFragment;
            Spinner mGameSpinner;
            LinearLayout mSpinnerLayout;
    
            public MyViewHolder(View view, final PopularFragment mPopularFragment, final String userId) {
                super(view);
                this.mPopularFragment = mPopularFragment;
                mSpinnerLayout = (LinearLayout) view.findViewById(R.id.spinner_layout);
                title = (TextView) view.findViewById(R.id.item_title);
                thumbnail = (ImageView) view.findViewById(R.id.item_main_img);
                mCardView = (CardView) view.findViewById(R.id.item_cardview);
                mCardView.setOnClickListener(this);
    
                mGameSpinner = (Spinner) view.findViewById(R.id.game_spinner_options);
                mGameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
                        //String ASIN = gameDataArr.get(position).getAmazonId();
                        System.out.println(parent.getId());     // <--- prints the same value for each item.
                        if(userId == null){
                            Toast.makeText(mPopularFragment.getActivity(), "You must be logged in.", Toast.LENGTH_LONG).show();
                            return;
                        }
                        FirebaseDbHelper mFirebaseDbHelper = new FirebaseDbHelper();
                        if(position == 0){
                            // remove from db
                           // mFirebaseDbHelper.removeOwnedGame(ASIN, userId);
                        } else if(position == 1){
                            // add to owned games
                           // mFirebaseDbHelper.addOwnedGame(ASIN, userId);
                        } else {
                            // add to wishlist games
                          //  mFirebaseDbHelper.addWishlistGame(ASIN, userId);
                        }
                    }
    
                    @Override
                    public void onNothingSelected(AdapterView<?> adapterView) {
    
                    }
                });
            }
    
            @Override
            public void onClick(View view) {
                System.out.println("click: " + getPosition());
                //mPopularFragment.openGameActivity(getPosition());
            }
        }
    
    
        @Override
        public PopularAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            System.out.println("parent: " + parent);
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_item, parent, false);
    
            return new PopularAdapter.MyViewHolder(itemView, mPopularFragment, userId);
        }
    
        @Override
        public void onBindViewHolder(final PopularAdapter.MyViewHolder holder, final int position) {
            GameData game = gameDataArr.get(position);
            holder.title.setText(game.getTitle());
            Picasso.with(mContext).load(game.getFeatImgUrl()).resize(160, 200).into(holder.thumbnail);
    
        }
    
        @Override
        public int getItemCount() {
            return gameDataArr.size();
        }
    
    
    }
    

    CardView

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/item_cardview"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_marginBottom="0dp"
        card_view:cardCornerRadius="4dp"
        >
    
        <LinearLayout
            android:padding="16dp"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <ImageView
                android:id="@+id/item_main_img"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_toLeftOf="@+id/right_content"
                android:scaleType="fitXY"
                android:adjustViewBounds="false"/>
    
            <LinearLayout
                android:id="@+id/right_content"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
    
                <TextView
                    android:id="@+id/item_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="16dp" />
    
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">
    
                    <Spinner
                        android:id="@+id/game_spinner_options"
                        android:entries="@array/game_dropdown"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"></Spinner>
    
                    <Button
                        android:text="Buy Now"
                        android:id="@+id/game_buy_btn"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"/>
    
                </LinearLayout>
    
            </LinearLayout>
    
        </LinearLayout>
    
    </android.support.v7.widget.CardView>
    

    Popular Fragment

    public class PopularFragment extends Fragment {
    
        @BindView(R.id.popular_recyclerView)
        RecyclerView mPopularRecyclerView;
        private RecyclerView.Adapter mAdapter;
    
        private ArrayList<GameData> gamesArray = new ArrayList<GameData>();
        ApiResultsObject apiResults;
        private FirebaseAuth auth;
        private FirebaseUser user;
        private FirebaseAuth.AuthStateListener authListener;
        private String userId;
    
        public PopularFragment() {
            // Required empty public constructor
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_popular, container, false);
            ButterKnife.bind(this, view);
            // bus instance
            MyBus.getInstance().register(this);
    
            // get api url
            // trigger async task
            // use results
            String amazonApiUrl = getAmazonApiUrl();
            if(amazonApiUrl != null){
                new AmazonAsyncTask().execute(amazonApiUrl);
            }
    
            //get firebase auth instance
            auth = FirebaseAuth.getInstance();
            //get current user
            user = FirebaseAuth.getInstance().getCurrentUser();
    
            //add a auth listener
            authListener = new FirebaseAuth.AuthStateListener() {
                @Override
                public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                    FirebaseUser user = firebaseAuth.getCurrentUser();
                    if (user != null) {
                        // User is signed in
                        System.out.println("User logged in. Game activity.");
                        userId = user.getUid();
    
                    } else {
                        // User is signed out
                        System.out.println("User not logged in. Game activity");
    
                    }
                }
            };
    
            // Inflate the layout for this fragment
            return view;
        }
    
        private String getAmazonApiUrl() {
            String amazonApiUrl = "";
            AmazonQuery amazonQuery = new AmazonQuery("ItemSearch");
            amazonApiUrl = amazonQuery.buildUrl();
            return amazonApiUrl;
        }
    
        private void setData(ApiResultsObject data) {
            gamesArray = data.getGamesArray();
            if (data != null) {
                mAdapter = new PopularAdapter(getActivity().getBaseContext(), gamesArray, this, userId);
                RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
                mPopularRecyclerView.setLayoutManager(mLayoutManager);
                mPopularRecyclerView.setAdapter(mAdapter);
    
            }
        }
    
    
    
        @Subscribe
        public void onAsyncTaskResults(BrowseAsyncTaskResult event) {
            apiResults = event.getResults();
            if (apiResults != null) {
                setData(apiResults);
            }
        }
    
        @Override
        public void onDestroy() {
            MyBus.getInstance().unregister(this);
            super.onDestroy();
        }
    
        @Override
        public void onStart() {
            super.onStart();
            auth.addAuthStateListener(authListener);
        }
    
        @Override
        public void onStop() {
            super.onStop();
            if (authListener != null) {
                auth.removeAuthStateListener(authListener);
            }
        }
    }
    
  • jdoyle1331
    jdoyle1331 about 7 years
    This works with an OnItemSelectedListener. Thanks for the help!
  • karthik kolanji
    karthik kolanji over 6 years
    OnItemSelectedListener gives position of the spinner values , but what about position of recyclerview ?
  • karthik kolanji
    karthik kolanji over 6 years
    YOU cannot set OnClickListener to spinner
  • MarkInTheDark
    MarkInTheDark over 6 years
    @karthikkolanji Why not? I'm pretty sure I was able to back when I posted my answer and it worked fine. Granted, it is not the optimal way as I have realized since then. So what do you mean?
  • karthik kolanji
    karthik kolanji over 6 years
    I tried ... It throws error ." You cannot set OnClickListener() to spinner"