1. 程式人生 > >Android 設定控制元件按寬:高=4:3顯示

Android 設定控制元件按寬:高=4:3顯示

先來見效果圖:


如果想向上圖展示的那樣,實現圖片或是控制元件按照寬高比例進行顯示,當然最先想到的是用weight,但是又一想weight只適用於螢幕寬度按比例分配,但是高度要怎麼設定呢,所以weight方法不行。

那應該用什麼方法呢,能做到寬:高=4:3的比例顯示?所以想到了自定義控制元件:

step1:首先自定義一個名叫LoweImageView的類:

<pre name="code" class="java">public class LoweImageView extends ImageView {
	/**
	 * 圖片比例. 比例=寬/高
	 */
	private float mRatio;

	public LoweImageView(Context context) {
		this(context, null);
	}

	public LoweImageView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public LoweImageView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context, attrs);
	}

	/**
	 * 初始化
	 * 
	 * @param context
	 *            上下文
	 * @param attrs
	 *            屬性
	 */
	private void init(Context context, AttributeSet attrs) {
		TypedArray typedArray = context.obtainStyledAttributes(attrs,
				R.styleable.LoweImageView);
		mRatio = typedArray.getFloat(R.styleable.LoweImageView_ratio, 0);
		typedArray.recycle();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// 寬模式
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		// 寬大小
		int widthSize = MeasureSpec.getSize(widthMeasureSpec);
		// 高大小
		int heightSize;
		// 只有寬的值是精確的才對高做精確的比例校對
		if (widthMode == MeasureSpec.EXACTLY && mRatio > 0) {
			heightSize = (int) (widthSize / mRatio + 0.5f);
			heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize,
					MeasureSpec.EXACTLY);
		}
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
}

step2:上面程式碼中的R.styleable.LoweImageView、R.styleable.LoweImageView_ratio是不是不知道在哪呢?我來告訴你吧,在res/values/attrs檔案中:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="LoweImageView">
        <!-- 比例=寬/高 -->
        <attr name="ratio" format="float" />
    </declare-styleable>
</resources>

step3:最後一步就是在xml中引用了:

<com.qing.autolayout.LoweImageView
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        android:src="@drawable/picture"
        app:ratio="1.333" />

其中1.333就是你需要設定的寬:高的float型比例(當然,可以改成你需要的比例)。現在開始Run你的專案,就會出現寬高按比例的顯示。

總之,就是隻要寬的長度確定了,那麼高度就會按照你設定的比例進行顯示。上面是ImageView的示例,當然可以把ImageView換成Button、LinearLayout、RelativeLayout等等等,都是相同的道理。

另外,附上原始碼下載地址:demo地址