在xml文件中添加ListView控件:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F5F5F5" >
</ListView>
</LinearLayout>
自定义ListView控件列表项的显示内容,新建一个items.xml文件(按自己的需求定义):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants"
android:id="@+id/items">
<TextView
android:layout_width="100dp"
android:layout_height="match_parent"
android:gravity="center"
android:text="目标IP:"
android:textSize="25sp" />
<EditText
android:id="@+id/editIP"
android:layout_width="200dp"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:enabled="false"
android:textSize="25sp" />
<TextView
android:layout_width="120dp"
android:layout_height="match_parent"
android:gravity="center"
android:text="目标端口:"
android:textSize="25sp" />
<EditText
android:id="@+id/editport"
android:layout_width="130dp"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:enabled="false"
android:textSize="25sp" />
<Button
android:id="@+id/check_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="查看连接"
android:textSize="25sp"
android:focusable="false" />
</LinearLayout>
先在LinearLayout中添加android:descendantFocusability="blocksDescendants",Button按钮添加android:focusable="false",然后就可以为按钮添加单击事件;如果不这样做按钮的单击事件可能会无法执行。
在代码中的操作:
public static List<Map<String, Object>> socketitems;
public static Map<String, Object> map;
public static MySimpleAdapter socketadapter; //自定义适配器
public void onCreate(Bundle savedInstanceState) {
socketitems = new ArrayList<Map<String, Object>>();
socketadapter = new MySimpleAdapter(this,socketitems, R.layout.items,
new String[] {"InetAddress", "Port"}, new int[] {R.id.editIP, R.id.editport});
listView.setAdapter(socketadapter);
map = new HashMap<String, Object>();
map.put("InetAddress", s.getInetAddress().toString()); //为其中的控件添加数据
map.put("Port", Integer.toString(s.getPort()));
socketitems.add(map); //添加数据
socketadapter.notifyDataSetChanged(); //刷新列表
}
自定义适配器:
class MySimpleAdapter extends SimpleAdapter{ public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); // TODO Auto-generated constructor stub } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View v= super.getView(position, convertView, parent); //获取点击的列表项 //定义按钮单击事件 Button check_btn = (Button)v.findViewById(R.id.check_btn); check_btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //控件的操作 } }); return v; } }