gpt4 book ai didi

android - 在循环中动态添加 Spinner

转载 作者:行者123 更新时间:2023-11-29 16:14:37 24 4
gpt4 key购买 nike

我正在循环中添加 say 'n' 个微调器。但是当我运行我的代码时,只有最后添加的微调器是可见的。请在下面查看我的代码

Context context = this;
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();

ArrayList<String> hi = new ArrayList<String>();
hi.add("Test 1");
hi.add("Test 2");

list.add(hi);

ArrayList<String> hi1 = new ArrayList<String>();
hi1.add("Test 3");
hi1.add("Test 4");

list.add(hi1);

AlertDialog.Builder alert = new AlertDialog.Builder(context);

alert.setTitle("Test App");
alert.setMessage("Testing");


for (int i = 0; i < 2; i++) {
final Spinner spinner = (Spinner) layout
.findViewById(R.id.spinner1);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list.get(i));

dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
alert.setView(spinner);
}

alert.show();

最佳答案

这是因为您在 for 中所做的一切循环正在搜索 SpinnerActivity ' 布局然后使用 setView AlertDialog 的方法添加它(此方法不会将 View 添加到其他 Views 已经存在,它只是替换它们)。如果要添加多个Spinner同样AlertDialog你应该这样做:

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < 2; i++) {
Spinner spinner = new Spinner(this);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list.get(i));
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ll.addView(spinner, params);
}
alert.setView(ll);

编辑:您可以使用适当的布局管理器添加更多 View 。例如,对于 TextView和一个 Spinner在同一行你可以使用 TableLayout :

    TableLayout tl = new TableLayout(this);
for (int i = 0; i < 2; i++) {
TableRow tr = new TableRow(this);
TextView t = new TextView(this);
t.setText("Text " + i);
TableRow.LayoutParams params1 = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
tr.addView(t, params1);
Spinner spinner = new Spinner(this);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list.get(i));
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
TableRow.LayoutParams params2 = new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT);
tr.addView(spinner, params2);
TableLayout.LayoutParams trParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
tl.addView(tr, trParams);
}
alert.setView(tl);

关于android - 在循环中动态添加 Spinner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10460489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com