close
參考:http://huli.logdown.com/posts/280137-android-custo...
先在activity_main.xml裡新增一個ListView (@+id/listView),如下圖:
把ListView每一列看成一個View,
我的View需要6個TextView,放幣別、匯率等資料,例如:
幣別 現金買入 即期買入 Currency 現金賣出 即期賣出 |
美金 33.26500 33.56500 USD 33.80700 33.66500 |
所以建立了一個list_cell.xml來達成這個layout。
接下來建立一個class來放這些資料,名為ExchangeRate.java。
接著回到Activity裡加入以下程式:
private ListView listView; List<ExchangeRate> exchangeRateList = new ArrayList<ExchangeRate>(); private MyAdapter adapter; listView = (ListView) findViewById(R.id.listView); exchangeRateList.add(new ExchangeRate("幣別", "Currency", "現金買入", "現金賣出", "即期買入", "即期賣出")); exchangeRateList.add(new ExchangeRate("美金", "USD", "33.26500", "33.80700", "33.56500", "33.66500")); adapter = new MyAdapter(MainActivity.this, exchangeRateList); listView.setAdapter(adapter); |
MyAdapter.java的實作如下:
public class MyAdapter extends BaseAdapter{ private LayoutInflater myInflater; private List<ExchangeRate> exchangeRates; public MyAdapter(Context context,List<ExchangeRate> exchangeRate){ myInflater = LayoutInflater.<em>from</em>(context); this.exchangeRates = exchangeRate; } /*private view holder class*/ private class ViewHolder { TextView txtCur_zh; TextView txtCur_en; TextView txtCash_buy; TextView txtCash_sell; TextView txtSpot_buy; TextView txtSpot_sell; public ViewHolder(TextView txtCur_zh, TextView txtCur_en, TextView txtCash_buy, TextView txtCash_sell, TextView txtSpot_buy, TextView txtSpot_sell){ this.txtCur_zh = txtCur_zh; this.txtCur_en = txtCur_en; this.txtCash_buy = txtCash_buy; this.txtCash_sell = txtCash_sell; this.txtSpot_buy = txtSpot_buy; this.txtSpot_sell = txtSpot_sell; } } @Override public int getCount() { return exchangeRates.size(); } @Override public Object getItem(int arg0) { return exchangeRates.get(arg0); } @Override public long getItemId(int position) { return exchangeRates.indexOf(getItem(position)); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView==null) { convertView = myInflater.inflate(R.layout.list_cell, null); holder = new ViewHolder( (TextView) convertView.findViewById(R.id.currency_zh), (TextView) convertView.findViewById(R.id.currency_en), (TextView) convertView.findViewById(R.id.cash_buy), (TextView) convertView.findViewById(R.id.cash_sell), (TextView) convertView.findViewById(R.id.spot_buy), (TextView) convertView.findViewById(R.id.spot_sell) ); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } ExchangeRate exchangeRate = (ExchangeRate)getItem(position); holder.txtCur_zh.setText(exchangeRate.getCurrency_zh()); holder.txtCur_en.setText(exchangeRate.getCurrency_en()); holder.txtCash_buy.setText(exchangeRate.getCash_buy()); holder.txtCash_sell.setText(exchangeRate.getCash_sell()); holder.txtSpot_buy.setText(exchangeRate.getSpot_buy()); holder.txtSpot_sell.setText(exchangeRate.getSpot_sell()); return convertView; } } |
可以執行程式看看結果。
全站熱搜
留言列表