假设我有ListView
一些物品。我想这样当用户点击一个项目时,应用程序会弹出一个Toast
包含项目名称的内容。例如,当用户点击“苹果”时,他们会看到吐司:“你吃了苹果”。我该怎么做?
问问题
921 次
4 回答
1
标准的使用方式.setOnItemClickListener()
。
于 2013-05-31T12:15:55.370 回答
0
试试这个代码 listview=(ListView)findViewById(R.id.listid);
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long arg3) {
// to set your list item or name
//here list is your list that you set in your adapter
list.get(pos);
}
});
于 2013-05-31T12:49:06.960 回答
0
像这样使用
活动列表视图.java
package com.sunil;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ActivityListView extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an array of Strings, that will be put to our ListActivity
String[] namesArray = new String[] { "Linux", "Windows7", "Eclipse",
"Suse", "Ubuntu", "Solaris", "Android", "iPhone" };
/* Create an ArrayAdapter, that will actually make the Strings above
appear in the ListView */
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, namesArray));
}
@Override
protected void onListItemClick(ListView l, View v,
int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
Toast.makeText(this, "You selected: " + keyword,
Toast.LENGTH_SHORT).show();
}
}
主.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
于 2013-05-31T12:17:07.433 回答
0
您可以在列表视图上设置项目单击侦听器,即
listvw=(ListView)findViewById(R.id.listviewid);
listvw.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Toast.makeText(ActivityName.this, "Text message", Toast.LENGTH_SHORT).show();
}
});
于 2013-05-31T12:23:05.163 回答