gpt4 book ai didi

java - 如何为listView实现onclicklistener

转载 作者:行者123 更新时间:2023-12-01 13:10:46 24 4
gpt4 key购买 nike

我有一个 Activity (MainActivity),它调用第二个 Activity (ImageAndTextAdapter)来显示 ListView 。我希望能够单击每个列表项来打开一个新 Activity 。但是我不知道如何正确实现 setOnItemClickListener 函数。我尝试了很多不同的方法。任何帮助将不胜感激。

主要 Activity :

public class MainActivity extends ListActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Context ctx = getApplicationContext();
Resources res = ctx.getResources();

String[] options = res.getStringArray(R.array.country_names);
TypedArray icons = res.obtainTypedArray(R.array.country_icons);

setListAdapter(new ImageAndTextAdapter(ctx, R.layout.main_list_item, options, icons));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;}


}

ImageAndTextAdapter.java:

public class ImageAndTextAdapter extends ArrayAdapter<String> {

private LayoutInflater mInflater;

private String[] mStrings;
private TypedArray mIcons;

private int mViewResourceId;

public ImageAndTextAdapter(Context ctx, int viewResourceId,
String[] strings, TypedArray icons) {
super(ctx, viewResourceId, strings);

mInflater = (LayoutInflater)ctx.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);

mStrings = strings;
mIcons = icons;

mViewResourceId = viewResourceId;
}

@Override
public int getCount() {
return mStrings.length;
}

@Override
public String getItem(int position) {
return mStrings[position];
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);

ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon);
iv.setImageDrawable(mIcons.getDrawable(position));

TextView tv = (TextView)convertView.findViewById(R.id.option_text);
tv.setText(mStrings[position]);

return convertView;
}
}

XML 文件:

<resources>
<string-array name="country_names">
<item>Columbia</item>
<item>Peru</item>
<item>Argentina</item>
</string-array>
<array name="country_icons">
<item>@drawable/Columbia</item>
<item>@drawable/Peru</item>
<item>@drawable/Argentina</item>
</array>
</resources>

最佳答案

在 onCreate() 方法中,在 setListAdapter(new ImageAndTextAdapter(ctx, R.layout.main_list_item, options, Icons)); 之后,使用:

getListView().setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// Handle your click here as you want

}
});

关于java - 如何为listView实现onclicklistener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22887378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com