編輯:關於 Android 程式設計
PreferenceActivity 天生適合做設置界面,但外觀實在單調。想在其中插入自定義內容(筆者當時是為了塞一條 @有米 v4 廣告),就需要動點手腳。
首先要明確一點:PreferenceScreen 的配置文件放在 res/xml 目錄下,並不屬於 layout 資源。要往裡嵌布局,有兩條路。
1)在 xml 配置文件中添加 Preference 節點:
<Preference android:layout="@layout/youmi_ad" android:key="youmi_ad"/>
2)編寫 res/layout/youmi_ad.xml:
<?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="wrap_content">
<!-- 有米廣告 -->
<akai.settings.YoumiAd
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal" />
</LinearLayout>
3)由於 v4 版本的廣告條需要自定義 layout 載體,這裡重載了一個 LinearLayout,其他自定義布局也是同樣思路。
public class YoumiAd extends LinearLayout {
public YoumiAd(Context context) {
super(context);
init(context);
}
public YoumiAd(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
AdView adView = new AdView(context, AdSize.SIZE_320x50);
this.addView(adView);
adView.setAdListener(new AdViewLinstener() {
@Override
public void onSwitchedAd(AdView arg0) {
Log.i("Youmi", "廣告條切換");
}
@Override
public void onReceivedAd(AdView arg0) {
Log.i("Youmi", "請求廣告成功");
}
@Override
public void onFailedToReceivedAd(AdView arg0) {
Log.i("Youmi", "請求廣告失敗");
}
});
}
}
1)xml 中的 Preference 添加方式相同:
<Preference android:layout="@layout/youmi_ad" android:key="youmi_ad"/>
2)layout 中必須包含一個 id 為 @android:id/list 的 ListView,否則無法運行——畢竟 PreferenceActivity 本身就是基於 List 的:
<?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="wrap_content">
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:layout_weight="1" />
<!-- 有米廣告 -->
<LinearLayout
android:id="@+id/adLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal" />
</LinearLayout>
3)在 Activity 的 onCreate 中加入 setContentView(R.layout.youmi_ad);,之後就能用 findViewById 獲取自定義布局裡的控件了。
兩種方案的取捨很直白:方法一侵入性小、結構清晰;方法二自由度更高,適合需要整體改造設置頁的場景。
Android 模仿 Flappy Bird 的遊戲開發實作解析
本文以仿 Flappy Bird 的小遊戲為例,說明如何使用 Android 原生繪製能力完成一個簡單休閒遊戲。重點包括遊戲物件封裝、SurfaceView 繪製、遊戲狀
Android 中獲取控件寬高與屏幕寬高的多種方法
一、獲取屏幕寬高 1. Android 界面結構簡介 要獲取屏幕寬高,不妨先了解 Android 界面的構成。它由三部分組成:狀態欄、標題欄、內容區域。 (1)狀態欄
驗證碼倒計時按鈕實現:Android賬號注冊常見交互
為防止惡意刷短信或郵件,注冊頁面的「獲取驗證碼」按鈕通常都要做倒計時處理:點擊後按鈕變灰並開始倒數,倒數結束才能再次點擊。本文分享一個可複用的封裝思路。 效果預覽 Re
Android 四大元件終極篇:Service 完整解析(啟動服務、綁定服務與生命週期)
Service 是 Android 四大元件之一,用來在後台執行長時間的操作而不需要使用者介面。典型用途包括網路傳輸、播放音樂、檔案讀寫,或與 ContentProvid