我有一个RecyclerView通过适配器实现CardViews的LinearLayout。在每个CardView中,我都有一个微调器。我需要做的是在选择微调器时获得CardViews位置。例如,如果我在屏幕上的列表中有10个CardViews,每个都有一个微调器,并且在第5项中从微调器中选择一个值,那么我需要获得该第5个位置以及所选值。

我可以得到选定的值。问题在于获取CardViews位置。 CardViews是从ArrayList生成的。

我将在下面包含我的代码以及所需结果的图像。任何帮助是极大的赞赏!!

java - 选中后,Android Spinner在RecyclerView中获取当前 View-LMLPHP

RecyclerView适配器

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


}


卡视图

<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>


流行片段

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

最佳答案

您可以在onBindViewHolder()中的mGameSpinner上设置OnClickListener。

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


然后,您可以存储/使用position参数,因为它将成为该特定微调器的gameArray的索引。然后,您可以使用该索引来获取微调框的当前选定值,并使用该索引进行任何操作。

08-03 23:31