gpt4 book ai didi

android - Spinner 的 setOnItemSelectedListener 不调用

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:16:09 25 4
gpt4 key购买 nike

我使用 setOnItemSelectedListener 来指定在微调器中选择了哪个项目,但我认为它没有被调用。它应该在程序运行时打印“It works”。

XML代码:

<Spinner
android:id="@+id/quantity"
android:layout_width="94dp"
android:layout_height="27dp"
android:layout_x="11dp"
android:layout_y="118dp"
/>

Java代码:

public class quantity extends Activity
{

Spinner quantity;


public void onCreate(Bundle savedInstanceState)
{
quantity=(Spinner)findViewById(R.id.quantity);

quantity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
Object item = parent.getItemAtPosition(pos);

System.out.println("it works... ");

}

public void onNothingSelected(AdapterView<?> parent)
{

}
});


}

}

最佳答案

试试这个

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Your_Layout);

//to fill your Spinner
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("Item 1");
spinnerArray.add("Item 2");
spinnerArray.add("Item 3");
spinnerArray.add("Item 4");
spinnerArray.add("Item 5");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) findViewById(R.id.quantity);
spinner.setAdapter(adapter);

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
Object item = adapterView.getItemAtPosition(position);
if (item != null) {
Toast.makeText(MainActivity.this, item.toString(),
Toast.LENGTH_SHORT).show();
}
Toast.makeText(MainActivity.this, "Selected",
Toast.LENGTH_SHORT).show();

}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {
// TODO Auto-generated method stub

}
});
}

关于android - Spinner 的 setOnItemSelectedListener 不调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16581536/

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