Android自定義用戶控件簡單範例(一)

一款優秀的移動應用須要具備本身獨特統一的風格,一般狀況下UI設計師會根據產品需求和使用人羣的特色,設計總體的風格,界面的元素和控件的互效果。而原生態的Android控件爲開發人員提供的是最基本的積木元素,若是要準確地傳遞統一的視覺效果和交互體驗,對控件的自定義使用是很是有必要的。前端

Android開發也採用前端xml+後端Java的形式進行頁面開發,寫過C#的人應該知道,xml是一種界面元素佈局的直觀顯示,根據標籤自動完成編譯顯示給用戶,無需運行時才能看到界面,這樣的分離能減少代碼的耦合而且方便調試。但本質上去除xml佈局文件,依然是能夠完成全部的程序設計。這篇文章經過一個簡單的徹底從Java後臺程序中進行建立的示例來講明Android自定義控件的運行原理。android

下面是一個簡單的自定義控件,繼承LinearLayout,加一個居中的ImageView和TextView。後端

    private void initView(Context context){
        setOrientation(VERTICAL);
        // 定義佈局填充形式,該佈局的寬和高均根據內容自適應調整
        ViewGroup.LayoutParams wrap_wrapParams = new LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        setLayoutParams(wrap_wrapParams);
        setGravity(Gravity.CENTER);
        
        LinearLayout.LayoutParams params = new LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        
        imageView = new ImageView(context);
        imageView.setId(10001);
        
        textView = new TextView(context);
        textView.setId(10002);
        
        addView(imageView, params);
        addView(textView, params);
    } 
    
    /*設置顯示文字*/
    public void setTextViewText(String text){
        textView.setText(text);
    }

若是要用xml進行描述以下:ide

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical" >
    
    <!-- Display a button -->
    <ImageView
        android:id="@+id/icon_part"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />
        <!-- android:src="@drawable/ic_action_share" -->

    <TextView
        android:id="@+id/text_part"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>
</LinearLayout>
View Code

調用的時候直接:佈局

相關文章
相關標籤/搜索