RecyclerView中的Android Spinner在选中时获取当前视图

时间:2017-02-27 17:02:08

标签: java android xml android-recyclerview android-spinner

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

我能够很好地获得所选值。问题在于获得CardViews的位置。 CardViews是从ArrayList生成的。

我将在下面包含我的代码以及所需结果的图像。非常感谢任何帮助!!

enter image description here

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


}

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>

热门片段

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

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

我认为您应该通过onBindViewHolder中的持有人为RV中的每个视图设置一个标记。类似的东西:

holder.itemView.setTag(game.getId());

游戏的ID应该是您传递到ArrayList的{​​{1}}中的数据点之一。因此,向Adpater对象添加getId()方法会更容易。

一旦你有一个整数ID要调用,这对于列表中的每个游戏都是唯一的,你可以在Spinner的game中找到Id:

onItemSelectedListener

然后,您可以在if-else语句中使用int ID = (int) holder.itemView.getTag();来了解卡片列表中哪个游戏被选中。[/ p>

答案 2 :(得分:0)

@Override     public void onBindViewHolder(final LanguagesAdapter.MyViewHolder持有人,最终int位置){

    holder.edit_language_name.setText(edit_languageDetails_ArrayList.get(position).getEt_language_name());
     sp_langage_rating=edit_languageDetails_ArrayList.get(position).getEt_language_ratings();
    String ss=sp_langage_rating;


    if(sp_langage_rating != null) {
      if(sp_langage_rating.equals("Beginner"))
      {
          adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language);
          adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
          holder.sp_languages.setAdapter(adapterLanguage);
      }
      else if(sp_langage_rating.equals("Intermediate")) {

          adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language1);
          adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
          holder.sp_languages.setAdapter(adapterLanguage);

      }else if(sp_langage_rating.equals("Expert")){
          adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language2);
          adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
          holder.sp_languages.setAdapter(adapterLanguage);
      }


    }else{
        adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language);
        adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        holder.sp_languages.setAdapter(adapterLanguage);
    }




    Log.d("print","yes");

}