在 Android 自定義 Button 類別中修改文字顏色,只需在初始化方法中調用 setTextColor() 即可,支援顏色資源、十六進制值或 Color 類常量。
public class CustomButton extends Button {
// ... 構造方法 ...
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "MyCustomFont.otf");
setTypeface(tf);
// 缺少文字顏色設置
}
}
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "MyCustomFont.otf");
setTypeface(tf);
// 方法一:使用 Color 類常量
setTextColor(Color.BLUE);
// 方法二:使用顏色資源 (API 23+)
// setTextColor(ContextCompat.getColor(getContext(), R.color.my_text_color));
// 方法三:十六進制值
// setTextColor(0xFFFF0000); // 紅色
// 方法四:ColorStateList 支援不同狀態顏色
// setTextColor(getResources().getColorStateList(R.color.button_text_selector));
}
}
無需自定義類別,直接在 XML 中設置:
<com.example.CustomButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自定義按鈕"
android:textColor="#FF0000"
android:textSize="16sp" />
res/color/button_text_selector.xml:
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#FFFFFF" />
<item android:state_focused="true" android:color="#FFFF00" />
<item android:state_enabled="false" android:color="#888888" />
<item android:color="#000000" /> <!-- 默認 -->
</selector>
應用:
// 代碼中
setTextColor(ContextCompat.getColorStateList(context, R.color.button_text_selector));
// XML 中
android:textColor="@color/button_text_selector"
setTextColor(int) 接受單一顏色值,setTextColor(ColorStateList) 接受狀態列表getResources().getColor(),API 23+ 建議 ContextCompat.getColor()init() 中設置,確保所有構造方法都調用AppCompatButton,主題屬性 colorButtonNormal 等可能影響背景但不影響文字顏色