gpt4 book ai didi

android - 来自另一个方法的微调器 setSelection() 导致空指针异常

转载 作者:行者123 更新时间:2023-11-29 18:13:39 27 4
gpt4 key购买 nike

类(class) build

protected Spinner tipSpinner;
private ArrayAdapter<CharSequence> adapterTip;

在 setContentView(R.layout.main) 之后的 onCreate 中;

Spinner spinner= (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapterTip = ArrayAdapter.createFromResource(this, R.array.tipArray, android.R.layout.simple_spinner_item);
adapterTip.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterTip);
spinner.setSelection(14, true);
spinner.setOnItemSelectedListener(new tipSelectorListener());

微调监听器

public class tipSelectorListener implements OnItemSelectedListener{

public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) {
Toast.makeText(parent.getContext(), "TEST " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}

public void onNothingSelected(AdapterView parent){
//Do Nothing
}

}

EditText 输入 - 在键更改时调用计算,更改微调器的值

billAmount = (EditText)findViewById(R.id.textLblBillAmount);
EditText billAmount = (EditText) findViewById(R.id.textLblBillAmount);

billAmount.setOnKeyListener(new EditText.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press

recalculate();
//Spinner tipSpinner.setSelection(0, true);

Toast toast = Toast.makeText(getBaseContext(), "TEST", Toast.LENGTH_SHORT);
toast.show();

return true;
}
return false;
}
});

计算方法

public void recalculate(){
// Recalculate Values of all
tipSpinner.setSelection(0, true);

}

EditText Changed 时出现 Null Pointer 错误,认为这有 c

最佳答案

您没有初始化 tipSpinner 变量。

更改此代码:

Spinner spinner= (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapterTip = ArrayAdapter.createFromResource(this,
R.array.tipArray, android.R.layout.simple_spinner_item);
adapterTip.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterTip);
spinner.setSelection(14, true);
spinner.setOnItemSelectedListener(new tipSelectorListener());

给这个:

tipSpinner= (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapterTip = ArrayAdapter.createFromResource(this,
R.array.tipArray, android.R.layout.simple_spinner_item);
adapterTip.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
tipSpinner.setAdapter(adapterTip);
tipSpinner.setSelection(14, true);
tipSpinner.setOnItemSelectedListener(new tipSelectorListener());

关于android - 来自另一个方法的微调器 setSelection() 导致空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9368693/

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