我正在尝试为 ListView 中的项目创建一个 onlcicklistener,但我不知道从哪里开始。我尝试了几件事,但没有一个奏效。这是该类的代码:
public class Primary_Weapons extends Activity {
private ListView listView1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.we_primary_list);
Weapon weather_data[] = new Weapon[]
{
new Weapon(R.drawable.we_braton, "Braton"),
new Weapon(R.drawable.we_braton_prime, "Braton Prime"),
new Weapon(R.drawable.we_braton_vandal, "Braton Vandal"),
new Weapon(R.drawable.we_braton, "MK1-Braton"),
new Weapon(R.drawable.we_boltor, "Boltor")
};
WeaponAdapter adapter = new WeaponAdapter(this,
R.layout.listview_item_row, weather_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
}
单击一个项目时,其上的文本将定义一个字符串,然后该字符串将用于另一个方法。例如,如果选择了“Braton Prime”,它会将字符串设置为“Braton Prime”,然后将用于做其他事情
编辑:适配器代码:
public class WeaponAdapter extends ArrayAdapter<Weapon>{
Context context;
int layoutResourceId;
Weapon data[] = null;
public WeaponAdapter(Context context, int layoutResourceId, Weapon[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weapon weather = data[position];
holder.txtTitle.setText(weather.title);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
编辑 3:基本上我希望 listView 上的每个项目做一些不同的事情