我非常接近让我的微调器在选择项目时做某事。我无法弄清楚如何正确设置onitemselectedlistener。我认为我的问题是不知道如何将参数传递给我的onItemSelected方法。非常感谢帮助完成这项工作的最后部分。
以下是代码:
public class MainActivity extends AppCompatActivity {
Spinner spinner;
String[][] testScoreList = new String[3][3];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Load test scores into arraylist
nameArrayListMethod();
spinner.setOnItemSelectedListener(onItemSelected());
}
//This method loads test scores into an array and populates spinner
public void nameArrayListMethod (){
InputStreamReader InputSR = null;
BufferedReader BufferedRdr = null;
String thisLine = null;
AssetManager am = getAssets();
String[] SpinnerNames = new String[3];
try {
InputSR = new InputStreamReader(am.open("scoresdata/test_scores.txt"));
BufferedRdr = new BufferedReader(InputSR);
// open input stream test_scores for reading purpose.
int i = 0;
while ((thisLine = BufferedRdr.readLine()) != null) {
//System.out.println(thisLine);
String[] parts = thisLine.split(" ");
testScoreList[i][0] = parts[0];
testScoreList[i][1] = parts[1];
testScoreList[i][2] = parts[2];
SpinnerNames[i] = testScoreList[i][0]; //Extract first column for spinner
i = i +1;
}
BufferedRdr.close();
InputSR.close();
} catch (Exception e) {
e.printStackTrace();
}
spinner= (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, SpinnerNames);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:1)
看起来像:
spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
});
答案 1 :(得分:1)
试试这个
{{1}}
答案 2 :(得分:1)
您可以添加数据方式
方法1
如果您有一个简单的单行数据,请使用此方法。
第1步
在string.xml文件中添加字符串数组
<string-array name="ArrayName">
<item>A</item>
<item>B</item>
<item>C</item>
<item>D</item>
<item>E</item>
<item>F</item>
</string-array>
在xml微调器组件中添加 android:entries="@string/ArrayName"
并使用String text = spinner.getSelectedItem().toString();
Spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText(topThis, "Value = "+spinner.getSelectedItem().toString();, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "herf", Toast.LENGTH_LONG).show();
}
});
方法2
使用自定义适配器HERE是完整的教程