我一直在修改一些来自udacity的代码。
https://github.com/udacity/ud839_CustomAdapter_Example
我想在其他活动中使用列表中的选择。我通常使用祝酒消息来测试是否成功选择了正确的项目等。但是,即使我的祝酒消息也使应用程序崩溃。
下面是arraylist,listview和onitemclicklistener的简化版本。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an ArrayList of AndroidFlavor objects
final ArrayList<AndroidFlavor> androidFlavors = new ArrayList<AndroidFlavor>();
androidFlavors.add(new AndroidFlavor("Lollipop", "5", R.drawable.lollipop));
androidFlavors.add(new AndroidFlavor("Nougat", "7", R.drawable.nougat));
androidFlavors.add(new AndroidFlavor("Oreo", "8", R.drawable.oreo));
// Create an {@link AndroidFlavorAdapter}, whose data source is a list of
// {@link AndroidFlavor}s. The adapter knows how to create list item views for each item
// in the list.
final AndroidFlavorAdapter flavorAdapter = new AndroidFlavorAdapter(this, androidFlavors);
// Get a reference to the ListView, and attach the adapter to the listView.
ListView listView = (ListView)findViewById(R.id.listview_flavor);
listView.setAdapter(flavorAdapter);
下面是我认为会导致问题的代码,如果我手动传递字符串,但不会传递所选列表项,则onItemClick会起作用。 androidFlavors.get(position)似乎不正确,但我不确定为什么。
//onClickItemListener to take selected Arraylist component and display the selected component in a toast message
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
Toast.makeText(getApplicationContext(), (CharSequence) androidFlavors.get(position), Toast.LENGTH_SHORT).show();
}
});
}
}
答案 0 :(得分:2)
您正在尝试将new AndroidFlavor("Nougat", "7", R.drawable.nougat)
强制转换为CharSequence
。相反,您应该使用getVersionName
。
Toast.makeText(getApplicationContext(), androidFlavors.get(position).getVersionName(), Toast.LENGTH_SHORT).show();