Android 1.6
有一组这样的对象
public class MyItem {
public String name = "";
public String brief = "";
public int availiableweight = 0;
public Node xmlpoint = null;
@Override
public String toString()
{
return name;
}
public MyItem(String _brief, String _name, Node _xmlpoint)
{
name = _name;
brief = _brief;
xmlpoint = _xmlpoint;
}
}
对象存储在array:ArrayList itemsList中
项目在微调器的下拉列表中可见,但我无法选择任何项目.未生成事件OnItemSelectedListener.微调控件是空的.我的错在哪里?
申请代码
public class MyActivity extends Activity {
/** Called when the activity is first created. */
private ArrayList itemsList;
private Spinner mySpinner;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mySpinner = (Spinner) findViewById(R.id.mySpinner);
itemsList = new ArrayList();
ArrayAdapter myAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, itemsList);
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(myAdapter);
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView> arg0, View arg1,
int arg2, long arg3)
{
// TODO Auto-generated method stub
AlertDialog("Pos: " + arg2);
}
@Override
public void onNothingSelected(AdapterView> arg0)
{
// TODO Auto-generated method stub
}
});
itemsList.add(new MyItem("1","one",null));
itemsList.add(new MyItem("2","two",null));
itemsList.add(new MyItem("3","three",null));
}
}
layout main.xml
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
android:id="@+id/languageText"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="Language" android:gravity="center_vertical"/>
android:id="@+id/languageSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" android:prompt="@string/chooseitem"/>
解决方法:
你的问题在这里:
ArrayAdapter myAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, itemsList);
由于您有一组自定义对象,因此无法使用通用ArrayAdapter类.在ArrayAdapter的构造函数中,您使用android.R.layout.simple_spinner_item布局文件.但适配器不知道如何显示您的数据.
您必须使用自定义适配器并创建自己的XML布局文件.
阅读一些如何实现这一目标的例子.最好了解ListView和适配器的工作原理.
看到这些链接:
它们提供了非常好的参考.您可以继续阅读“Android列表”系列教程的下一部分,以扩展您的知识.
希望这可以帮助.如果您需要进一步解释,请务必发表评论.
标签:android,spinner,android-arrayadapter
来源: https://codeday.me/bug/20190902/1792170.html