动态添加的微调框为空

问题描述 投票:0回答:1

所以我的应用程序中有一个活动,可以动态添加和删除字段,默认情况下,已经有一个字段。原始微调器包含所有信息,我可以在其中选择任何对象,但是动态添加的微调器为空。如何动态添加填充的微调器?我试着在addField方法中调用填充方法,但是这样做没有帮助,并使事情变得更奇怪了。添加新字段时的外观如下:enter image description here

这里是添加字段的方法:

public void addField(View v) {
        if(parentLayout.getChildCount() < maxCourses) {
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View rowView = inflater.inflate(R.layout.field, null);
            //add new row before add field button
            parentLayout.addView(rowView, parentLayout.getChildCount() - 1);
        } else {
            Toast.makeText(this, "No more than " + maxCourses + " courses\ncan be taken per semester", Toast.LENGTH_SHORT).show();
        }
    }

这是我通过“ ADD COURSE”按钮进行的​​称呼

addFieldBtn = findViewById(R.id.add_field_btn);
        addFieldBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addField(v);
            }
        });

这是字段。新生成的字段的XML代码,它们与原始填充字段具有相同的ID

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:background="@color/colorSecondaryDark"
    android:layout_alignParentBottom="true">

    <Spinner
        android:id="@+id/first_spinner"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:spinnerMode="dropdown" />

    <Button
        android:id="@+id/remove_field_button"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@color/colorSecondary"
        android:gravity="center"
        android:onClick="removeField"
        android:text="REMOVE\nCOURSE"
        android:textSize="12sp" />

</LinearLayout>

[如果有人可以给我一些提示或帮助,我将不胜感激!

java android android-layout dynamic spinner
1个回答
0
投票

新的微调器不知道从何处获取数据。您应该为每个新微调器设置一个适配器。喜欢这里:

public void addField(View v) {
    if(parentLayout.getChildCount() < maxCourses) {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View rowView = inflater.inflate(R.layout.field, null);
        Spinner spinner = rowView.findViewById(R.id.first_spinner);
        ArrayAdapter<String> arrayAdapter = getAnAdapterForThatSpinner();
        spinner.setAdapter(arrayAdapter)
        //add new row before add field button
        parentLayout.addView(rowView);
    } else {
        Toast.makeText(this, "No more than " + maxCourses + " courses\ncan be taken per semester", Toast.LENGTH_SHORT).show();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.