动态多重微调器 "setOnItemSelectedListener()" 无法处理项目点击 - Android

Dynamic multiple spinners "setOnItemSelectedListener()" is not working on item click - Android

我正在循环中使用 ViewGroup 动态创建多个 Spinner,我成功地做到了,但是当我从微调器中选择一个项目时,setOnItemSelectedListener() 不会调用该项目选择.相反,它会在微调器创建和值填充之后第一次调用。

我认为 Spinner 的实例在创建后会被破坏,或者我使用监听器的方式有误。

这里可以看到我的相关代码:

        List<SpinnerItem> arrSpinnerItem;
        List<AppCompatSpinner> arrSpinners = new ArrayList<>();
    
    
          // here is the function
           //outer loop to create spinners
        for (int i = 0; i < 2; i++) {
            LinearLayout newView = (LinearLayout) getLayoutInflater().inflate(R.layout.view_linear_layout, null);
            newView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            AppCompatSpinner spinner = newView.findViewById(R.id.view_spinner);
//                        AppCompatSpinner spinner = new AppCompatSpinner(context);
            spinner.setTag(i);
            arrSpinners.add(spinner); //adding instance for the listener

            //inner loop to add items to the created spinner
            arrSpinnerItem = new ArrayList<>();
            for (int j = 0; j < 2; j++) {
                arrSpinnerItem.add(new SpinnerItem("id", "name"));
            }

            //spinner adapter
            if (arrSpinnerItem.size() > 0)
                spinner.setAdapter(new SpinnerItemAdapter(context, R.layout.item_spinner, arrSpinnerItem));

            layout_viewContainer.addView(newView);

        }

        //listener for all creating spinners
        for (AppCompatSpinner compatSpinner : arrSpinners)
            compatSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) { //=> ERROR: doesn't invoke on item click
                    Log.e(TAG, "callback: " + arrSpinners.get(position).getSelectedItem());
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });0

activity_main.xml

<LinearLayout
        android:id="@+id/addSale2Act_layout_viewContainer"
        android:padding="@dimen/_10sdp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    </LinearLayout>

SpinnerItem.java

public class SpinnerItem {
    private String id, name;

    public SpinnerItem(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return name;
    }
}

view_linear_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_marginTop="@dimen/_20sdp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@drawable/shape_rec_spinner"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <androidx.appcompat.widget.AppCompatImageView
        android:layout_width="@dimen/_18sdp"
        android:layout_height="@dimen/_18sdp"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:layout_marginEnd="@dimen/_10sdp"
        android:paddingTop="@dimen/_4sdp"
        app:srcCompat="@drawable/ic_arrow_down" />

    <androidx.appcompat.widget.AppCompatSpinner
        android:id="@+id/view_spinner"
        style="@style/RippleEffect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:background="@android:color/transparent"
        android:gravity="center"
        android:spinnerMode="dropdown" />
    </RelativeLayout>

</LinearLayout>

解决方案:

创建 arrays.xml 将所有 spinner itemlist 放入应用程序 ---> 资源 ---> 布局

<?xml version="1.0" encoding="utf-8"?>

<resources>
    <string-array name="myarray">
      <item>Itemname1</item>
      <item>Itemname2</item>
      <item>Itemname3</item>
      <item>Itemname4</item>
      <item>Itemname5</item>
    </string-array>
</resources>

然后编辑MainActivity

public class MainActivity extends AppCompatActivity {

    private static final String TAG ="" ;
    private ArrayAdapter<String> SpinnerAdapter;

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


        List<SpinnerItem> arrSpinnerItem;
        final List<AppCompatSpinner> arrSpinners = new ArrayList<>();
        ViewGroup layout_viewContainer = (ViewGroup) findViewById(R.id.addSale2Act_layout_viewContainer);


        for (int i = 0; i < 2; i++) {

            LinearLayout newView = (LinearLayout) getLayoutInflater().inflate(R.layout.view_linear_layout, null);
            newView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            AppCompatSpinner spinner = newView.findViewById(R.id.view_spinner);

            SpinnerAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, getResources()
                    .getStringArray(R.array.myarray));

            SpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(SpinnerAdapter);
            spinner.setTag(i);

            arrSpinners.add(spinner); //adding instance for the listener

            //inner loop to add items to the created spinner
            arrSpinnerItem = new ArrayList<>();
            for (int j = 0; j < 2; j++) {
                arrSpinnerItem.add(new SpinnerItem( "name"));
            }


           if (arrSpinnerItem.size() > 0)
            {
                try {
                    addSpinnerListener(spinner);
                }
                catch(Exception e)
                {
                    Toast.makeText(getApplicationContext(), ""+e, Toast.LENGTH_LONG ).show();
                }
            }
           //     spinner.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_item, arrSpinnerItem));

            layout_viewContainer.addView(newView);

        }


    }


    private void addSpinnerListener(final Spinner curspinner) {

        curspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {

                ((TextView) adapterView.getChildAt(0)).setTextColor(Color.BLACK);
                String strselected = curspinner.getSelectedItem().toString();

                int spinnerPosition = SpinnerAdapter.getPosition(strselected);
                curspinner.setSelection(spinnerPosition);
               
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


    }
}