編輯:Android 開發實例
ListView 表面上是個列表,但只要願意在 item 布局上下功夫,完全可以做成一個像樣的表格。本文以股票行情為例:紅色代表上漲,綠色代表下跌,表頭固定不動,列表獨立滾動。

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="color_dark_grey">#808080</color>
<color name="color_black">#000000</color>
<color name="color_green">#00FF00</color>
<color name="color_red">#FF0000</color>
<color name="color_white">#FFFFFF</color>
</resources>
表格之所以像表格,關鍵在於那幾條細細的分割線。這裡抽成兩個樣式,一個負責橫向、一個負責縱向。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 列表項分隔線 -->
<style name="list_item_seperator_layout">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">1dip</item>
<item name="android:background">@color/color_dark_grey</item>
</style>
<!-- 單元格之間的豎向分隔線 -->
<style name="list_item_cell_seperator_layout">
<item name="android:layout_width">1dip</item>
<item name="android:layout_height">fill_parent</item>
<item name="android:background">@color/color_dark_grey</item>
</style>
</resources>
用 TableLayout + TableRow 拼出五列,每兩列之間插入一個空的 View 作為豎線。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="3">
<TableRow android:id="@+id/stock_list_header_row">
<View />
<TextView
android:id="@+id/stock_list_header_code"
android:text="@string/stock_code"
android:layout_width="60dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="2dip" />
<View />
<TextView
android:id="@+id/stock_list_header_symbol"
android:text="@string/stock_symbol"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="2dip" />
<View />
<TextView
android:id="@+id/stock_list_header_last_price"
android:text="@string/stock_last_price"
android:layout_width="60dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="2dip" />
<View />
<TextView
android:id="@+id/stock_list_header_price_change"
android:text="@string/stock_price_change"
android:layout_width="50dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="2dip" />
<View />
<TextView
android:id="@+id/stock_list_header_price_change_percentage"
android:text="@string/stock_price_change_percent"
android:layout_width="50dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="2dip" />
<View />
</TableRow>
</TableLayout>
</LinearLayout>
那些 <View /> 就是豎向的分割線,撐開相鄰單元格的距離。android:stretchColumns="3" 則保證某一列能吃掉剩餘空間,避免右邊留白。
結構和表頭保持一致,列寬也必須對齊,這樣上下才能形成視覺上的「表格」。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableLayout
android:id="@+id/stock_list_item_table_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="3">
<TableRow android:id="@+id/stock_list_row">
<View />
<TextView
android:id="@+id/stock_code"
android:layout_width="60dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="2dip" />
<View />
<TextView
android:id="@+id/stock_symbol"
android:layout_width="1dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="2dip" />
<View />
<TextView
android:id="@+id/stock_last_price"
android:layout_width="60dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="2dip" />
<View />
<TextView
android:id="@+id/stock_change_price"
android:layout_width="50dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="2dip" />
<View />
<TextView
android:id="@+id/stock_change_percentage"
android:layout_width="50dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="2dip" />
<View />
</TableRow>
</TableLayout>
</LinearLayout>
這裡有個關鍵設計:表頭並不是用 ListView 自帶的 addHeaderView,而是通過 include 直接放在 ListView 上方。原因很簡單——這樣滾動時表頭會永遠釘在頂部,不會跟著列表一起滑走。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<View />
<include layout="@layout/stock_list_header" />
<View />
<ListView
android:id="@+id/stock_list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollingCache="true"
android:cacheColorHint="#00000000"
android:fastScrollEnabled="true"
android:focusable="true"
android:divider="@color/color_dark_grey"
android:dividerHeight="1dip" />
</LinearLayout>
上下兩個空 View 用來在表頭邊緣畫線,把表頭和數據區分開。cacheColorHint 設為全透明則是為了避免滾動時出現黑色塊。
Activity 主要做三件事:讀取用戶偏好(字號、背景色、漲跌配色)、初始化表頭、把 Cursor 交給 Adapter。
package com.android.msoft.mfinance.ui;
import com.android.msoft.mfinance.R;
import com.android.msoft.mfinance.provider.Stock;
import com.android.msoft.mfinance.provider.StockMarket.StockMarketColumns;
import com.android.msoft.mfinance.ui.MFinancePreferenceActivity.BGColor;
import com.android.msoft.mfinance.ui.MFinancePreferenceActivity.TextSize;
import com.android.msoft.mfinance.ui.MFinancePreferenceActivity.UpDownColor;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;
public class StockListActivity extends Activity {
private static final String TAG = "com.android.msoft.mfinance.ui.StockListActivity";
private SharedPreferences mPreference;
private TextView mCodeTextView;
private TextView mSymbolTextView;
private TextView mLastPriceTextView;
private TextView mPriceChangeTextView;
private TextView mPriceChangePercentageTextView;
private ListView mStockListView;
private TableRow mStockListHeader;
private float mTextSize;
private int mBgColor;
private int mDownTextColor;
private int mUpTextColor;
private Cursor mStockListCursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.stock_list);
mPreference = PreferenceManager.getDefaultSharedPreferences(this);
refreshDisplayPreference();
mStockListHeader = (TableRow) findViewById(R.id.stock_list_header_row);
mCodeTextView = (TextView) findViewById(R.id.stock_list_header_code);
mSymbolTextView = (TextView) findViewById(R.id.stock_list_header_symbol);
mLastPriceTextView = (TextView) findViewById(R.id.stock_list_header_last_price);
mPriceChangeTextView = (TextView) findViewById(R.id.stock_list_header_price_change);
mPriceChangePercentageTextView = (TextView) findViewById(
R.id.stock_list_header_price_change_percentage);
mStockListView = (ListView) findViewById(R.id.stock_list_view);
refreshStockListHeader();
mStockListCursor = getContentResolver().query(
Stock.CONTENT_URI_STOCK_WITH_MARKET, null, null, null,
StockMarketColumns.CHANGE_PRICE_PERCENT + " DESC");
StockListAdapter listViewAdpater = new StockListAdapter(this, mStockListCursor);
mStockListView.setAdapter(listViewAdpater);
}
@Override
protected void onDestroy() {
if (!mStockListCursor.isClosed()) {
mStockListCursor.close();
}
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.stock_list_option_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.stock_list_option_menu_settings:
startActivity(new Intent(this, MFinancePreferenceActivity.class));
break;
}
return super.onOptionsItemSelected(item);
}
private void refreshDisplayPreference() {
UpDownColor upAndDownColor = MFinancePreferenceActivity.UpDownColor
.valueOf(mPreference.getString("up_down_color", "RED_GREEN"));
if (0 == upAndDownColor.value) { // 漲紅跌綠
mUpTextColor = getResources().getColor(R.color.color_red);
mDownTextColor = getResources().getColor(R.color.color_green);
} else { // 漲綠跌紅
mUpTextColor = getResources().getColor(R.color.color_green);
mDownTextColor = getResources().getColor(R.color.color_red);
}
TextSize textSize = MFinancePreferenceActivity.TextSize
.valueOf(mPreference.getString("text_size", "NORMAL"));
mTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
textSize.value, getResources().getDisplayMetrics());
int colorResId = R.color.color_black;
BGColor bgColor = MFinancePreferenceActivity.BGColor
.valueOf(mPreference.getString("bg_color", "BLACK"));
switch (bgColor.value) {
case 0:
colorResId = R.color.color_black;
break;
case 1:
colorResId = R.color.color_white;
break;
default:
Log.e(TAG, "invalid bg color");
}
mBgColor = getResources().getColor(colorResId);
}
public float getTextSize() {
return mTextSize;
}
public int getBgColor() {
return mBgColor;
}
public int getUpTextColor() {
return mUpTextColor;
}
public int getDownTextColor() {
return mDownTextColor;
}
private void refreshStockListHeader() {
mCodeTextView.setTextSize(mTextSize);
mSymbolTextView.setTextSize(mTextSize);
mLastPriceTextView.setTextSize(mTextSize);
mPriceChangeTextView.setTextSize(mTextSize);
mPriceChangePercentageTextView.setTextSize(mTextSize);
mStockListHeader.setBackgroundColor(mBgColor);
mStockListView.setBackgroundColor(mBgColor);
}
}
繼承 BaseAdapter,內部包一個 Cursor。列索引在構造函數裡一次性查好,避免 getView 中反覆調用 getColumnIndex 帶來的開銷。
package com.android.msoft.mfinance.ui;
import com.android.msoft.mfinance.provider.Stock.StockColumns;
import com.android.msoft.mfinance.provider.StockMarket.StockMarketColumns;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class StockListAdapter extends BaseAdapter {
private static final String TAG = "com.android.msoft.mfinance.ui.StockListAdapter";
private Cursor mStockListCursor;
private Context mContext;
private final int sCodeIndex;
private final int sSymbolIndex;
private final int sBoardIndex;
private final int sLastPriceIndex;
private final int sChangePriceIndex;
private final int sChangePricePercentIndex;
public StockListAdapter(Context context, Cursor cursor) {
mStockListCursor = cursor;
mContext = context;
sCodeIndex = mStockListCursor.getColumnIndex(StockColumns.CODE);
sSymbolIndex = mStockListCursor.getColumnIndex(StockColumns.SYMBOL);
sBoardIndex = mStockListCursor.getColumnIndex(StockColumns.BOARD);
sLastPriceIndex = mStockListCursor.getColumnIndex(StockMarketColumns.LAST_PRICE);
sChangePriceIndex = mStockListCursor.getColumnIndex(StockMarketColumns.CHANGE_PRICE);
sChangePricePercentIndex = mStockListCursor
.getColumnIndex(StockMarketColumns.CHANGE_PRICE_PERCENT);
}
@Override
public int getCount() {
Log.d(TAG, "Stock list count:" + mStockListCursor.getCount());
return mStockListCursor.getCount();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
StockListItem listItem;
mStockListCursor.moveToPosition(position);
if (null == convertView) {
String code = mStockListCursor.getString(sCodeIndex);
String symbol = mStockListCursor.getString(sSymbolIndex);
String board = mStockListCursor.getString(sBoardIndex);
float lastPrice = mStockListCursor.getFloat(sLastPriceIndex);
float changePrice = mStockListCursor.getFloat(sChangePriceIndex);
float changePercent = mStockListCursor.getFloat(sChangePricePercentIndex);
listItem = new StockListItem(mContext, code, symbol, board,
lastPrice, changePrice, changePercent);
} else {
listItem = (StockListItem) convertView;
}
return listItem;
}
}
讓列表項本身成為一個 LinearLayout 子類,在構造函數裡完成 inflate 和賦值。這樣 convertView 的複用就非常自然。
package com.android.msoft.mfinance.ui;
import com.android.msoft.mfinance.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
public class StockListItem extends LinearLayout {
public StockListItem(Context context, String code, String symbol,
String board, float lastPrice, float changePrice,
float changePercent) {
super(context);
StockListActivity stockListActivity = (StockListActivity) context;
float textSize = stockListActivity.getTextSize();
LayoutInflater factory = LayoutInflater.from(context);
factory.inflate(R.layout.stock_list_item, this);
TextView codeTextView = (TextView) findViewById(R.id.stock_code);
codeTextView.setTextSize(textSize);
codeTextView.setText(code);
TextView symbolTextView = (TextView) findViewById(R.id.stock_symbol);
symbolTextView.setTextSize(textSize);
symbolTextView.setText(symbol);
TextView lastPriceTextView = (TextView) findViewById(R.id.stock_last_price);
lastPriceTextView.setTextSize(textSize);
lastPriceTextView.setText(Float.toString(lastPrice));
TextView changePriceTextView = (TextView) findViewById(R.id.stock_change_price);
changePriceTextView.setTextSize(textSize);
changePriceTextView.setText(Float.toString(changePrice));
TextView changePercentTextView = (TextView) findViewById(R.id.stock_change_percentage);
changePercentTextView.setTextSize(textSize);
changePercentTextView.setText(Float.toString(changePercent));
if (changePrice > 0) {
int textColor = stockListActivity.getUpTextColor();
lastPriceTextView.setTextColor(textColor);
changePriceTextView.setTextColor(textColor);
changePercentTextView.setTextColor(textColor);
} else if (changePrice < 0) {
int textColor = stockListActivity.getDownTextColor();
codeTextView.setTextColor(textColor);
symbolTextView.setTextColor(textColor);
lastPriceTextView.setTextColor(textColor);
changePriceTextView.setTextColor(textColor);
changePercentTextView.setTextColor(textColor);
}
}
}
本文是用空 View 來畫線的。其實也可以給每個單元格設置不同的背景色,靠背景色塊的邊界形成分割效果,代碼量更少,不過在精細度上不如真正的線條。兩種思路可以按需選用。
Android 側滑菜單實現解析:自定義 ViewGroup 與 Path 風格動畫
側滑菜單的實現有兩條路:用成熟的開源庫,或者自己動手寫一個。本文走第二條路,重點在兩個部分——負責手勢與滾動的自定義 ViewGroup(FlipperLayout),以
Android JSON 解析完整指南:從 JSONObject 到天氣查詢 App 實作
JSON 的全名是 JavaScript Object Notation(JavaScript 物件符號法),它最大的優點是輕量、易讀,而且天生就適合在瀏覽器與伺服器之間
Android 端如何解析 JSON:以天氣查詢 App 為例
行動應用要顯示即時資訊,幾乎都得向伺服器要資料,而回傳格式十之八九是 JSON。它源自 JavaScript 的物件語法,但早已是語言中立的文字格式,任何平台都能讀。相比
Android 自定義 ImageView 實現透明圓弧與弧形文字
最近因為項目需求,需要在 ImageView 上疊加一層透明圓弧,並且沿著圓弧方向顯示相應的文字,效果如下圖所示: 拿到這個需求,我最直覺的思路就是自定義一個 Imag