在我的应用程序中,我有片段,其中包含微调器,按钮,editText和多个TextView。这是我获取用户所选项目并显示它的代码:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Get position
int index = productSpinner.getSelectedItemPosition();
int[] tableSpoonList = getResources().getIntArray(R.array.tableSpoon);
int[] glassList = getResources().getIntArray(R.array.glass);
int[] teaSpoonList = getResources().getIntArray(R.array.teaSpoon);
// Set the texts and defaults
if (glassList[index] == 0) {
typeGlass.setVisibility(View.INVISIBLE);
} else {
typeGlass.setText(getString(R.string.glass) + glassList[index] + getString(R.string.grams));
typeGlass.setVisibility(View.VISIBLE);
}
if (tableSpoonList[index] == 0) {
typeTablespoon.setVisibility(View.INVISIBLE);
} else {
typeTablespoon.setText(getString(R.string.table_spoon) + tableSpoonList[index] + getString(R.string.grams));
typeTablespoon.setVisibility(View.VISIBLE);
}
if (teaSpoonList[index] == 0) {
typeTeaspoon.setVisibility(View.INVISIBLE);
} else {
typeTeaspoon.setText(getString(R.string.tea_spoon) + teaSpoonList[index] + getString(R.string.grams));
typeTeaspoon.setVisibility(View.VISIBLE);
}
}
正如我所提到的,我有一个editText和一个按钮。我希望用户在editText中输入一个数字,然后用值进行一些计算,然后显示它。
我想出了解决方案,设置名为 convert 的按钮onCLick
:
public void convert (View view) {
int userInput = Integer.parseInt(valueInput.getText().toString());
if (userInput == 0) {
Toast.makeText(getContext(), "Enter the value!", Toast.LENGTH_SHORT).show();
} else {
double customTableSpoon = (1/tableSpoonList[index]) * userInput;
typeTablespoon.setText(Double.toString(customTableSpoon));
}
}
但正如你所看到的,我无法从
获得double customTableSpoon = (1/tableSpoonList[index]) * userInput;
tableSpoonlist [index] ,因为它是在微调器onItemSelected
中定义的。但是,如果我在 convert 方法
//Get position
int index = productSpinner.getSelectedItemPosition();
int[] tableSpoonList = getResources().getIntArray(R.array.tableSpoon);
int[] glassList = getResources().getIntArray(R.array.glass);
int[] teaSpoonList = getResources().getIntArray(R.array.teaSpoon);
切换到该片段时我崩溃了,因为
int index = productSpinner.getSelectedItemPosition();
返回null。
我无法在片段中实施onClick
,因为我已经在实施AdapterView.OnItemSelectedListener
。
此外,我的微调器是在创建视图上创建的:
//Create spinner
productSpinner = (Spinner) view.findViewById(R.id.productSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.products_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
productSpinner.setAdapter(adapter);
productSpinner.setOnItemSelectedListener(this);
如何获取旋转器选定项目,以便用户可以编辑&#34;它?