gpt4 book ai didi

java - 如何使用 Spinner(s) 值更新 Button Click 上的 TextView

转载 作者:行者123 更新时间:2023-11-30 04:51:57 24 4
gpt4 key购买 nike

我正在尝试根据 3 个 Spinner 中当前选定的选项填充 TextView,但似乎无法弄清楚如何从 Spinner 中检索选定的值以调用更新函数。这是我当前的代码(相当困惑,但我只是在学习 Java :)),

public class AgeFun extends Activity {
private String[] dayNames;
private String[] yearArray;
private final static int START_YEAR = 1990;
private static TextView textDisp;
private Button calcButton;
private static Spinner spinnerDay, spinnerYear, spinnerMonth;
private static ArrayAdapter<?> monthAdapter, dayAdapter, yearAdapter;
private int year, month, day;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

year = 2000;
month = 1;
day = 1;
textDisp = (TextView) findViewById(R.id.textView1);
calcButton = (Button) findViewById(R.id.button);
calcButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
AgeFun.updateAge(year, month, day);
}
});

// Month spinner
spinnerMonth = (Spinner) findViewById(R.id.spinnerFirst);
monthAdapter = ArrayAdapter.createFromResource(
this, R.array.monthList, android.R.layout.simple_spinner_item);
monthAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerMonth.setAdapter(monthAdapter);

// Day spinner
dayNames = new String[31];
for(int i =1; i <= 31; ++i)
{
dayNames[i-1] = Integer.toString(i);
}
spinnerDay = (Spinner) findViewById(R.id.spinnerSecond);
dayAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, dayNames);
spinnerDay.setAdapter(dayAdapter);

// Year spinner
yearArray = new String[40];
for(int i =0; i < 40; ++i)
{
yearArray[i] = Integer.toString(START_YEAR+i);
}
spinnerYear = (Spinner) findViewById(R.id.spinnerThird);
yearAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, yearArray);
spinnerYear.setAdapter(yearAdapter);

updateAge(2000,1,1);
}

private static void updateAge(int year, int month, int day) {
Date dob = new GregorianCalendar(year, month, day).getTime();
Date currDate = new Date();

long age = (currDate.getTime() - dob.getTime()) / (1000 * 60 * 60 * 24) / 365;
textDisp.setText("Your are " + Long.toString(age) + " years old");
}

任何帮助都会很棒。

TIA

最佳答案

可能这段代码有帮助(您可以使用 position 或 id 来定位适配器中的项目)

spnCountries.setOnItemSelectedListener(spnCountriesListener);


private Spinner.OnItemSelectedListener spnCountriesListener =

new Spinner.OnItemSelectedListener() {

public void onItemSelected(AdapterView parent, View v, int position, long id) {

Log.i("print", parent.getSelectedItem().toString());

}



public void onNothingSelected(AdapterView parent) { }

};

关于java - 如何使用 Spinner(s) 值更新 Button Click 上的 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3040085/

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