Android開發通過adapter顯示listview
阿新 • • 發佈:2018-11-27
首先,定義一個adapter繼承於某個ArrayAdapter,例項化adapter時將要顯示的peers傳遞進去,然後通過listview.setadapter(new adapter)顯示,
getview()方法決定每個item包含的資訊與顯示
adapter = new WiFiPeerListAdapter(WiFiDirectActivity.this, R.layout.row_devices, peers); listview.setadapter(adapter); private class WiFiPeerListAdapter extends ArrayAdapter<WifiP2pDevice> { private List<WifiP2pDevice> items; /** * @param context * @param textViewResourceId * @param objects */ public WiFiPeerListAdapter(Context context, int textViewResourceId, List<WifiP2pDevice> objects) { super(context, textViewResourceId, objects); items = objects; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) WiFiDirectActivity.this.getSystemService( Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.row_devices, null); } WifiP2pDevice device = items.get(position); if (device != null) { TextView top = (TextView) v.findViewById(R.id.device_name); TextView bottom = (TextView) v.findViewById(R.id.device_details); if (top != null) { top.setText(device.deviceName); } if (bottom != null) { bottom.setText(getDeviceStatus(device.status)); } } return v; } }