編輯:關於 Android 程式設計
本文示範如何透過自訂 Adapter 實現 ListView,並特別說明向下相容的考量:雖然 Android 提供了較新的方法,但為了相容舊版本系統,仍需採用向下相容的寫法。
public class MainActivity extends Activity {
private ListView listView;
private GameAdapter adapter;
private List
public class GameAdapter extends BaseAdapter {
private Context ctx;
private List> allValues;
public GameAdapter(Context ctx, List> allValues) {
this.ctx = ctx;
this.allValues = allValues;
}
@Override
public int getCount() {
return allValues.size();
}
@Override
public Object getItem(int position) {
return allValues.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(ctx).inflate(R.layout.my_adapter_item, null);
convertView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, Globals.SCREEN_HEIGHT / 10));
}
TextView imgText = (TextView) convertView.findViewById(R.id.line_img);
imgText.getLayoutParams().height = Globals.SCREEN_HEIGHT / 10;
TextView titleText = (TextView) convertView.findViewById(R.id.line_title);
TextView timeText = (TextView) convertView.findViewById(R.id.line_time);
Map map = allValues.get(position);
titleText.setText(map.get("title").toString());
timeText.setText(map.get("time").toString());
imgText.setBackgroundResource((Integer) map.get("img"));
return convertView;
}
}
getView 中的 convertView 是為了提高效能而準備的重用行元件,若目前行之前沒有建立過則為 null 需自行建立,否則只需修改其中的資料,形成元件循環利用。
public class Globals {
public static int SCREEN_WIDTH;
public static int SCREEN_HEIGHT;
public static void init(Activity a) {
// 初始化螢幕寬高,此方法不推薦使用,但為向下相容仍採用舊方法
SCREEN_WIDTH = a.getWindowManager().getDefaultDisplay().getWidth();
SCREEN_HEIGHT = a.getWindowManager().getDefaultDisplay().getHeight();
}
}
此處刻意採用 getWidth()、getHeight() 等舊方法,是因為新方法需 API 4.0 以上,而專案需相容 2.3 以上版本,因此仍使用舊方法以確保向下相容。

Android 開發:用 MediaRecorder 錄製影片
MediaRecorder 不只能錄音,也能錄影。整體流程與錄音幾乎一致,差別在於影片必須同時采集聲音與影像兩路資料。 因此除了呼叫 setAudioSource()
Web 開發實戰:演示 Servlet 生命週期並解決中文亂碼問題
本文以一個完整示例演示 Servlet 的生命週期,並重點講解解決中文亂碼問題的多種方法。至於更佳的方案——使用過濾器(Filter),這裡暫不展開,留待後續學習時再補充
深入理解 Android Gradle:生命週期、任務與實作筆記
Gradle 是 Android 的重要建置工具。它本身負責流程與規則,實際建置能力則由外掛提供,例如 Android App 外掛、Android Library 外掛
Day34 - Animation 動畫:補間、逐幀與屬性動畫一次講透
人眼存在視覺殘留現象,連續播放一系列靜態圖像,就會形成動畫效果。Android 中的動畫大致分為三類: · 遊戲動畫:利用自訂 View 的繪製方法,開啟執行緒高頻刷新介