編輯:關於 Android 程式設計
用 XML 寫佈局是 Android 開發的標準做法,它讓畫面結構與 Java 邏輯分離,程式碼讀起來清楚,改版也方便。但這種方便是有代價的:系統必須先解析 XML、再載入記憶體,佈局越複雜、巢狀越深,這段時間就越長;再加上不同解析度要準備多份 XML 檔,維護成本會隨頁面數量線性成長。
這篇文章記錄一個實際案例:同一個頁面,先用 XML 寫、再改用純 Java 程式碼建構,兩者的差異在哪裡。
頁面結構大致是「外層 RelativeLayout 包著左右兩個區塊,左區放控制按鈕,右區放相機預覽」:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/info_back">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/linearRecordLayout">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp">
<LinearLayout
android:id="@+id/contronLinearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp">
<!-- 溫度、濕度與方向控制按鈕群 -->
</LinearLayout>
<!-- 底部功能列 -->
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:id="@+id/camerSurfaceRelativelayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.pcareroute.surface.CameraSurfaceView
android:id="@+id/car_camera_surfaceview"
android:layout_width="wrap_content"
android:layout_height="fill_parent" />
</RelativeLayout>
</RelativeLayout>
寫完在 Eclipse 的圖形預覽裡看,一切正常:
但一上真機,結果就完全不是那回事。原本想呈現的畫面變了樣,於是我們做了第二次嘗試——針對不同解析度各寫一份 XML,一共三份佈局檔來硬扛適應性。這條路顯然走不遠:每改一個按鈕,三份檔都要同步改一次。
換個思路:把佈局拆成兩個檔案。一個負責組裝檢視樹,另一個專門存放所有尺寸參數,兩者分離後,調適應性時只需要改參數檔。
public class PcareRouteMain extends Activity {
public static final String TAG = "PcareRouteMain";
public PcareRouteMain instance;
PcareRouteParams pRouteParams;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ToolsUnility.getToolsUnilityInstance(this).noTitleAndStaBar(this);
instance = this;
pRouteParams = new PcareRouteParams(instance);
AppLog.enableLogging(true);
initLayout();
}
// 初始化佈局與元件
public void initLayout() {
Parent = new RelativeLayout(getApplicationContext());
Parent.setBackgroundResource(R.drawable.info_back);
// 底部按鈕列:用陣列批次產生,避免重複程式碼
BottomInParent = new LinearLayout(getApplicationContext());
BottomInParent.setId(_R.id.bottom_in_parent);
BottomInParent.setBackgroundResource(R.drawable.button_bar);
ButtonInBottom = new ToggleButton[pRouteParams.Bottom_Button_Number];
for (int i = 0; i < pRouteParams.Bottom_Button_Number; i++) {
ButtonInBottom[i] = new ToggleButton(getApplicationContext());
ButtonInBottom[i].setBackgroundResource(ButtonInBottomImage[i]);
ButtonInBottom[i].setTextOff(" ");
ButtonInBottom[i].setTextOn(" ");
ButtonInBottom[i].setText(" ");
BottomInParent.addView(ButtonInBottom[i],
pRouteParams.buttonInBottomParams);
}
Parent.addView(BottomInParent, pRouteParams.bottomInParentParams);
// 左側區塊:濕度、溫度、方向鍵
LeftInParent = new RelativeLayout(getApplicationContext());
LeftInParent.setId(_R.id.left_in_parent);
BottomInLeft = new LinearLayout(getApplicationContext());
BottomInLeft.setId(_R.id.bottom_in_left);
ButtonInLeft = new Button[pRouteParams.Left_Bottom_Button_Number];
for (int i = 0; i < pRouteParams.Left_Bottom_Button_Number; i++) {
ButtonInLeft[i] = new Button(getApplicationContext());
ButtonInLeft[i].setText(" ");
ButtonInLeft[i].setBackgroundResource(ButtonInLeftImage[i]);
BottomInLeft.addView(ButtonInLeft[i],
pRouteParams.Left_Bottom_Button_Params);
}
LeftInParent.addView(BottomInLeft, pRouteParams.bottomInLeftParams);
tempView = new TextView(getApplicationContext());
tempView.setTextSize(pRouteParams.Left_Top_Temp_TextSize);
tempView.setText("T:");
tempView.setId(_R.id.tempview_in_left);
LeftInParent.addView(tempView, pRouteParams.Left_Top_Temp_Params);
humidityView = new TextView(getApplicationContext());
humidityView.setText("H:");
humidityView.setId(_R.id.humiview_in_left);
humidityView.setTextSize(pRouteParams.Left_Top_Temp_TextSize);
LeftInParent.addView(humidityView, pRouteParams.Left_Top_Humi_Params);
CenterInLeft = new RelativeLayout(getApplicationContext());
ControlBtn = new Button[CtrolBtnNumber];
for (int i = 0; i < CtrolBtnNumber; i++) {
ControlBtn[i] = new Button(getApplicationContext());
ControlBtn[i].setBackgroundResource(Btn_Ctrol_In_Left_Image[i]);
CenterInLeft.addView(ControlBtn[i],
pRouteParams.Left_Center_CtrolButtons_Params[i]);
}
LeftInParent.addView(CenterInLeft, pRouteParams.Left_Center_CtrolButton_Params);
Parent.addView(LeftInParent, pRouteParams.leftInParentParams);
// 右側區塊:相機預覽與縮放
RightInParent = new RelativeLayout(getApplicationContext());
cameraSurface = new CameraSurface(getApplicationContext());
RightInParent.addView(cameraSurface, pRouteParams.Right_Surface_Params);
ScaleBtn = new Button[ScaleBtnNumber];
for (int i = 0; i < ScaleBtnNumber; i++) {
ScaleBtn[i] = new Button(getApplicationContext());
ScaleBtn[i].setBackgroundResource(Btn_Scale_In_Right_Image[i]);
RightInParent.addView(ScaleBtn[i],
pRouteParams.Right_Scale_Button_Params[i]);
}
scaleView = new TextView(getApplicationContext());
scaleView.setText("100%");
scaleView.getPaint().setFakeBoldText(true); // 加粗
scaleView.setTextSize(20);
RightInParent.addView(scaleView, pRouteParams.Right_Scale_View_Params);
Parent.addView(RightInParent, pRouteParams.RightInParentParams);
setContentView(Parent, pRouteParams.paramentParams);
}
// 圖示資源集中管理
public int[] ButtonInBottomImage = {
R.drawable.talk_off, R.drawable.music_off, R.drawable.video_off,
R.drawable.sound_mute, R.drawable.button_take_photo_icon,
R.drawable.ir_off, R.drawable.share_off};
public int[] ButtonInLeftImage = {
R.drawable.info_off, R.drawable.net_in_off, R.drawable.wifi_switch_off};
public int[] Btn_Ctrol_In_Left_Image = {
R.drawable.left_off, R.drawable.up_off,
R.drawable.right_off, R.drawable.down_off};
public int[] Btn_Scale_In_Right_Image = {
R.drawable.zoom_out, R.drawable.zoom_in};
public int CtrolBtnNumber = 4;
public int ScaleBtnNumber = 2;
}
用陣列批次產生同類元件,是這份程式碼最值得學的一點。四個方向鍵、七個底部功能鍵,如果用傳統寫法就是每個元件一個變數、一段 addView,程式碼膨脹好幾倍;改成陣列加迴圈之後,程式碼量直接除以 N,改動時也只需要動一個地方。
另一個檔案則負責把所有尺寸集中起來,並依螢幕大小分三個檔位:
public class PcareRouteParams {
Activity activity;
public PcareRouteParams(Activity activity) {
this.activity = activity;
getDisplayMetrics();
initVar();
initLayoutParams();
}
// 依螢幕尺寸決定各項間距與大小
public void initVar() {
if (screenSize > 5.8) {
Bottom_Button_Width = dip2px(60);
Left_Bottom_Button_Width = dip2px(35);
Bottom_Back_Height = dip2px(70);
Left_Top_Temp_TextSize = 35;
Left_Center_CtrolButton_Width = dip2px(300);
Left_Center_CtrolButton_Height = dip2px(250);
// ...其餘參數略
} else if (screenSize < 3.8) {
Bottom_Button_Width = dip2px(35);
Left_Bottom_Button_Width = dip2px(18);
Bottom_Back_Height = dip2px(35);
Left_Top_Temp_TextSize = 18;
Left_Center_CtrolButton_Width = dip2px(120);
Left_Center_CtrolButton_Height = dip2px(120);
// ...其餘參數略
} else {
Bottom_Button_Width = dip2px(40);
Left_Bottom_Button_Width = dip2px(27);
Bottom_Back_Height = dip2px(45);
Left_Top_Temp_TextSize = 18;
Left_Center_CtrolButton_Width = dip2px(150);
Left_Center_CtrolButton_Height = dip2px(150);
// ...其餘參數略
}
}
public int dip2px(float dpValue) {
return (int) (dpValue * scale + 0.5f);
}
// 取得螢幕寬高、密度,並換算對角線英寸數
public void getDisplayMetrics() {
DisplayMetrics dm = new DisplayMetrics();
dm = activity.getApplicationContext().getResources().getDisplayMetrics();
Screen_width = dm.widthPixels;
Screen_height = dm.heightPixels;
scale = dm.density;
density = dm.density;
double bb = Math.sqrt(Math.pow(Screen_width, 2)
+ Math.pow(Screen_height, 2));
screenSize = bb / (160 * dm.density);
}
// 建立 LayoutParams
public void initLayoutParams() {
paramentParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
bottomInParentParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, Bottom_Back_Height);
bottomInParentParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
// 底部按鈕均分寬度
buttonInBottomParams = new LinearLayout.LayoutParams(
Bottom_Button_Width, Bottom_Button_Width);
buttonInBottomParams.gravity = Gravity.CENTER_VERTICAL;
int jiange = (Screen_width - Bottom_Button_Width * Bottom_Button_Number)
/ (Bottom_Button_Number + 1);
buttonInBottomParams.leftMargin = jiange;
// 方向鍵:依上下左右分別定位
Left_Center_CtrolButtons_Params = new RelativeLayout.LayoutParams[4];
Left_Center_CtrolButtons_Params[0] = new RelativeLayout.LayoutParams(
Left_Center_CtrolButton_UpBtn_Height,
Left_Center_CtrolButton_UpBtn_Width);
Left_Center_CtrolButtons_Params[0].addRule(RelativeLayout.CENTER_VERTICAL);
Left_Center_CtrolButtons_Params[1] = new RelativeLayout.LayoutParams(
Left_Center_CtrolButton_UpBtn_Width,
Left_Center_CtrolButton_UpBtn_Height);
Left_Center_CtrolButtons_Params[1].addRule(RelativeLayout.CENTER_HORIZONTAL);
Left_Center_CtrolButtons_Params[2] = new RelativeLayout.LayoutParams(
Left_Center_CtrolButton_UpBtn_Height,
Left_Center_CtrolButton_UpBtn_Width);
Left_Center_CtrolButtons_Params[2].addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
Left_Center_CtrolButtons_Params[2].addRule(RelativeLayout.CENTER_VERTICAL);
Left_Center_CtrolButtons_Params[3] = new RelativeLayout.LayoutParams(
Left_Center_CtrolButton_UpBtn_Width,
Left_Center_CtrolButton_UpBtn_Height);
Left_Center_CtrolButtons_Params[3].addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
Left_Center_CtrolButtons_Params[3].addRule(RelativeLayout.CENTER_HORIZONTAL);
// 右側相機區
RightInParentParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
RightInParentParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
RightInParentParams.addRule(RelativeLayout.RIGHT_OF, _R.id.left_in_parent);
RightInParentParams.addRule(RelativeLayout.ABOVE, _R.id.bottom_in_parent);
RightInParentParams.leftMargin = Right_Surface_LeftMarge;
}
public float scale; // dp → px 換算比例
public double screenSize; // 螢幕對角線英寸數
public int Screen_width;
public int Screen_height;
public int Bottom_Button_Number = 7;
public int Left_Bottom_Button_Number = 3;
// ...其餘尺寸欄位略
}
真機上的呈現效果:
最終畫面看起來差不多,但底層是完全不同的兩套機制,取捨也很清楚:
選擇哪一種,取決於頁面的複雜度與變動頻率。像這個同時有相機預覽、方向控制、多列功能鍵的頁面,尺寸關係錯綜複雜,把參數抽出來集中管理確實省事很多。但對於一般的表單或列表頁,XML 加上好一點的 dimens.xml 與 ConstraintLayout,通常才是更划算的選擇——畢竟佈局寫在程式碼裡,三個月後回頭維護的人(很可能就是你自己)會需要一段時間才能看懂。
務實的做法是混合:靜態結構用 XML,需要動態計算或批次產生的部分用程式碼補上,中間透過 LayoutInflater 銜接。既保留可預覽的優勢,也不放棄程式化帶來的彈性。
Android 常用控制項入門整理:屬性、事件與繼承關係
溫故而知新。以下依據 Android 官方 API,整理一批常用控制項的常見用法(測試環境為 Android 4.4)。 一、TextView 從官方的類別繼承圖可以看
Android NDK 入門:從 JNI 到 so 庫
建立專案與宣告 JNI 先建立 Android 專案,新增 HelloJni 類別,用 loadLibrary 載入 native 函式庫,再用 native 宣告要由
Android AutoCompleteTextView 自動補全元件完整教學
AutoCompleteTextView 是什麼 AutoCompleteTextView 是可自動補全的輸入元件。當使用者輸入文字時,它會比對 Adapter 中的資料
用 HorizontalScrollView 仿 ViewPager 相冊:思路、代碼與 OOM 優化
前陣子看了一堂在線公開課,講的是如何用 HorizontalScrollView 仿造 ViewPager 做一個簡單相冊。核心思想其實是借鑑 ViewPager 的緩存