gpt4 book ai didi

android - 在android中的Spinner中实现键值对的正确方法是什么

转载 作者:IT王子 更新时间:2023-10-28 23:47:34 27 4
gpt4 key购买 nike

这是在 Android 中为 Spinner 实现键值对的正确方法吗?

package com.mypackage

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.TextView;

public class SpinnerAndAdapter extends Activity
{
TextView valueTextView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

valueTextView = (TextView)findViewById( R.id.selected );
Spinner s = (Spinner)findViewById(R.id.spinner);
final MyData items[] = new MyData[3];
items[0] = new MyData( "key1","value1" );
items[1] = new MyData( "key2","value2" );
items[2] = new MyData( "key3","value3" );
ArrayAdapter<MyData> adapter =
new ArrayAdapter<MyData>(
this,
android.R.layout.simple_spinner_item,
items );
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent,
View view,
int position,
long id) {
MyData d = items[position];
valueTextView.setText( d.getValue() );
}

public void onNothingSelected(AdapterView<?> parent) {
}
}
);
}

class MyData {
public MyData( String spinnerText, String value ) {
this.spinnerText = spinnerText;
this.value = value;
}

public String getSpinnerText() {
return spinnerText;
}

public String getValue() {
return value;
}

public String toString() {
return spinnerText;
}

String spinnerText;
String value;
}
}

最佳答案

这是一种方式。尽管我使用自己的适配器(从 BaseAdpater 继承),但我经常使用它。另一种方法是 b 希望上面有一个索引(0,1,2 等)映射到一个值,当你得到一个项目时,它的索引很好,这样你就可以从 map 中检索它的值。我不喜欢那个选项...

关于android - 在android中的Spinner中实现键值对的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5424841/

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