Android自定义控件之自定义EditText,令控件中的字根据控件高度自动调整大小-FenGKun

本文介绍了如何创建一个AdaptiveEdit类,该类继承自EditText,实现文字高度根据控件高度自动调整的功能。通过自定义控件,可以确保文字在编辑框内的显示效果始终保持最佳。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 文字高度会自适应的Edit
 * @author FenGKun
 *
 */
创建AdaptiveEdit类继承EditText

public class AdaptiveEdit extends EditText {
    private static String TAG = "AdaptiveEdit.java";
    private static boolean isDebug = false;

    /** 字大小与控件高的比例 */
    private float m_fTextSizeRatioViewHeight = 2.0f / 3;
    
    public AdaptiveEdit(Context context) {
        super(context);
        init(null);
    }
    
    public AdaptiveEdit(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }
    
    public AdaptiveEdit(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }
    
    private void init(AttributeSet attrs) {
    	// 读取用户配置的参数
        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.MyAdaptive);
            // 获取字大小与控件高的比例
            m_fTextSizeRatioViewHeight = typedArray.getFloat(R.styleable.MyAdaptive_TextSizeRatioViewHeight, 2.0f / 3);

            typedArray.recycle();
        }
    }
    
    @Override
	protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    	if (changed) {
	    	// 字大小与控件高的比例计算出字体的大小(单位像素)
	        setTextSize(TypedValue.COMPLEX_UNIT_PX, (getHeight() - getPaddingTop() - getPaddingBottom()) * m_fTextSizeRatioViewHeight);
    	}
    	
		if (isDebug) Log.e(TAG, "���ø߶�Ϊ��" + getHeight());
        
		super.onLayout(changed, left, top, right, bottom);
	}
    
}

布局文件中调用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<span style="color:#ff6666;">    xmlns:zf="http://schemas.android.com/apk/res/com.web8848.imf"</span>
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="#e0000000">
 <span style="white-space:pre">	</span><!-- 搜索内容 -->
	<com.web8848.imf.view.AdaptiveEdit android:id="@+id/edSeek"
	<span style="white-space:pre">	</span>android:layout_marginTop="1dp"
		android:layout_width="0dp"
		android:layout_weight="9.2"
		android:layout_height="match_parent"
		android:hint="请输入物品名称"
		android:textColor="#3C3E46"
		<span style="color:#ff6666;">zf:TextSizeRatioViewHeight="0.8"</span>
		android:gravity="center_vertical"/>
</LinearLayout>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值