我创建了一个Country.java类,并使我的自定义适配器myListAdapter扩展了ArrayAdapter。我的LogCat中没有任何消息,但是应用程序崩溃了:
countName.setText(" "+currentCountry.getCountryName());
所以这里有什么问题我怎么能得到CountryName?
public class Country{
private String countryName;
private String capitalName;
public Country(String countryName, String capitalName) {
this.countryName = countryName;
this.capitalName = capitalName;
}
public String getCountryName() {
return countryName;
}
public String getCapitalName() {
return capitalName;
}
}
这里是myListAdapter类
private class MyListAdapter extends ArrayAdapter<Country>{
public MyListAdapter() {
super(MainActivity.this, R.layout.item_view, myCountries);
}
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null){
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
Country currentCountry = myCountries.get(position);
TextView countName = (TextView) findViewById(R.id.item_countryName);
countName.setText(" "+currentCountry.getCountryName());
TextView capName = (TextView) findViewById(R.id.item_CapName);
capName.setText(currentCountry.getCapitalName());
return itemView;
}
}
item_view.xml是:
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/item_countryName" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/item_CapName" />
答案 0 :(得分:0)
Change the below code in your adapter :
TextView countName = (TextView) itemView.findViewById(R.id.item_countryName);
countName.setText(" "+currentCountry.getCountryName());
TextView capName = (TextView) itemView.findViewById(R.id.item_CapName);
capName.setText(currentCountry.getCapitalName());
编辑我的代码:
MyListAdapter adapter = new MyListAdapter(this,
R.layout.item_view, myCountries);
listView.setAdapter(adapter);
答案 1 :(得分:0)
您是手动触发getView()
方法吗?您应该@Override
此方法如下所示。如果您设置了适配器并且加载了屏幕,则会自动触发getView()
。
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
}
您应该使用下面的findViewById()
方法;
TextView countName = (TextView) itemView.findViewById(R.id.item_countryName);