Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義組合控件入門(一):圖片加文字的簡易實作

編輯:關於 Android 程式設計

前陣子參加了濟南的一場技術分享會,收穫不少,也很佩服願意無私分享的大神們。好東西大家一起分享,寫程式的人不能只當搬磚的碼農,總得有點追求。於是我下定決心,從最基礎的自定義控件開始學起。

自定義控件裡,組合控件大概是最容易上手的一種。本文就用最常見的「圖片 + 文字」組合來示範。

這樣的介面在許多 App 的首頁都能看到,圖片與文字內容都可以自行替換。

一、自定義 View 的程式碼

讓自定義類別繼承 LinearLayout,在初始化工時把 XML 版面配置填充進來,再透過 findViewById 取得內部控件,最後對外提供修改文字與圖片的公開方法。

package com.sdufe.thea.guo.view;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sdufe.thea.guo.R;

public class CustomView extends LinearLayout {

    private ImageView mImageView;
    private TextView mTextView;
    Context context;

    public CustomView(Context context) {
        super(context, null);
    }

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        View view = LayoutInflater.from(context)
                .inflate(R.layout.custom_view, this, true);
        mTextView = (TextView) view.findViewById(R.id.custom_textview);
        mImageView = (ImageView) view.findViewById(R.id.custom_imageview);
    }

    public void setText(String text) {
        mTextView.setText(text);
    }

    public void setTextColor(int color) {
        mTextView.setTextColor(color);
    }

    public void setTextSize(float size) {
        mTextView.setTextSize(size);
    }

    public void setImagViewResouce(Drawable drawable) {
        mImageView.setImageDrawable(drawable);
    }
}

二、控件自己的版面配置

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <ImageView
        android:id="@+id/custom_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/custom_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="嘿!" />
</LinearLayout>

三、在專案中引用

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true" >

        <com.sdufe.thea.guo.view.CustomView
            android:id="@+id/custom"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <com.sdufe.thea.guo.view.CustomView
            android:id="@+id/custom1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <com.sdufe.thea.guo.view.CustomView
            android:id="@+id/custom2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <com.sdufe.thea.guo.view.CustomView
            android:id="@+id/custom3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>
</RelativeLayout>
package com.sdufe.thea.guo;

import com.sdufe.thea.guo.view.CustomView;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Toast;

public class MainActivity extends Activity {

    private CustomView mCustomView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        mCustomView = (CustomView) findViewById(R.id.custom);
        mCustomView.setText("我是大壞蛋");
        mCustomView.setTextColor(getResources().getColor(R.color.text_color));
        mCustomView.setImagViewResouce(getResources().getDrawable(R.drawable.phone));
        mCustomView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "別點我", Toast.LENGTH_LONG).show();
            }
        });
    }
}

四、踩到的坑:inflate 為什麼不顯示

我平常填充版面配置習慣寫 LayoutInflater.from(context).inflate(resource, root),但在自定義控件裡這樣寫就是顯示不出來。翻過原始碼後改成三參數版本,一切就正常了:

LayoutInflater.from(context).inflate(R.layout.custom_view, this, true);

三個參數的意義分別是:

1. 第一個參數:要載入的版面配置 ID。
2. 第二個參數:為該版面配置在外層再嵌套一層父容器,不需要時可傳 null。
3. 第三個參數 attachToRoot:官方說明為「Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.」,也就是決定填充出來的層級要不要掛到 root 上;若為 false,root 只用來產生正確的 LayoutParams 子類別。

public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
    if (DEBUG) System.out.println("INFLATING from resource: " + resource);
    XmlResourceParser parser = getContext().getResources().getLayout(resource);
    try {
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}

繼續往下追,會發現它的實作基礎是 XML 的 Pull 解析,這裡先不展開。總結三個參數的行為:

1. root 為空時,attachToRoot 不生效。
2. root 不為空且 attachToRoot 為 true,會把版面配置的最外層掛到 root 上。
3. root 不為空且 attachToRoot 為 false,不會掛載最外層版面配置,只借用 root 產生 LayoutParams。

本篇先介紹如何用 Java 程式碼完成組合控件,下一篇再談如何透過自定義屬性(attr)來打造更通用的版本。

程式碼下載:https://download.csdn.net/detail/elinavampire/8141963

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved