我正在尝试为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上的每个项目做一些不同的事情
答案 0 :(得分:3)
只需在列表视图中设置一个监听器。
listView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Something like...
Weapon weapon = adapter.getItem(position);
textField.setText( weapon.getName() );
//...
}
});
答案 1 :(得分:1)
使用setOnItemClickListener
listView1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
}
});