主Activity
public class MainActivity extends Activity { private String[] data = new String[]{"测试数据1","测试数据2","测试数据3","测试数据4"}; private ListView listview; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listview = (ListView) this.findViewById(R.id.listView); listview.setAdapter(new SimpleAdapter(this, getData(), R.layout.item, new String[]{"text"} , new int[]{R.id.textView})); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub System.out.println("The item setOnItemClickListener id"+position); } }); listview.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub System.out.println("The item setOnItemSelectedListener id"+position); } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } }); } private List<HashMap<String,String>> getData(){ List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>(); HashMap<String, String> map = new HashMap<String, String>(); for (String text : data) { map.put("text", text); list.add(map); } return list; } public void button(View v){ System.out.println("The item button id"+listview.getPositionForView(v)); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" tools:context=".MainActivity" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent" > </ListView> </LinearLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:descendantFocusability="blocksDescendants" android:orientation="vertical" > <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="TextView" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:onClick="button" /> </LinearLayout>
主要两个属性
1.listview 的item 布局里加入;
android:descendantFocusability= "blocksDescendants"
2.button上加onClick,activity里加入onClick的实现
listview.getPositionForView(v)