gpt4 book ai didi

java - 具有空默认选定项的微调器

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:22:17 24 4
gpt4 key购买 nike

我正在尝试创建一个带有默认空选择项的微调器,但它显示了微调器选项中的第一个项目。如果我将空值添加到我的字符串中,这是微调器中选择的来源,那么在打开微调器之后会显示该空行。我应该怎么做?这是我正在使用的代码:

  String[] ch = {"Session1", "Session2", "Session3"};
Spinner sp = (Spinner)findViewById(R.id.spinner1);
TextView sess_name = findViewById(R.id.sessname);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ch);
sp.setAdapter(adapter);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener({
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
sess_name.setText(ch[index]);

Toast.makeText(getBaseContext(), "You have selected item : " + ch[index], Toast.LENGTH_SHORT).show();
}

最佳答案

Barak 的解决方案有问题。选择第一项时,Spinner 不会调用 OnItemSelectedListener 的 onItemSelected() 刷新空内容,因为前一个位置和选择位置都是 0。

首先在字符串数组的开头放置一个空字符串:

String[] test = {" ", "one", "two", "three"};

第二次构建适配器,不修改getView(),修改getDropDownView()。将空 View 的高度设置为 1px。

public class MyArrayAdapter extends ArrayAdapter<String> {

private static final int ITEM_HEIGHT = ViewGroup.LayoutParams.WRAP_CONTENT;

private int textViewResourceId;


public MyArrayAdapter(Context context,
int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
this.textViewResourceId = textViewResourceId;
}

@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
TextView textView;

if (convertView == null) {
textView = (TextView) LayoutInflater.from(getContext())
.inflate(textViewResourceId, parent, false);
} else {
textView = (TextView) convertView;
}

textView.setText(getItem(position));
if (position == 0) {
ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
layoutParams.height = 1;
textView.setLayoutParams(layoutParams);
} else {
ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
layoutParams.height = ITEM_HEIGHT;
textView.setLayoutParams(layoutParams);
}

return textView;
}
}

关于java - 具有空默认选定项的微调器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11483883/

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