Android初心者がカスタムボタンコントロールを使う
Androidではボタンタイプのビューを作成するためにButtonクラスを継承できます。この例では、丸みを帯びた背景とカスタマイズしたフォントを持つボタンタイプを作成する方法を示します。
まず、Buttonクラスを継承したCustomButtonというJavaクラスを作成する。
public class CustomButton extends Button {
public CustomButton(Context context) {
super(context);
init();
}
public CustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// 设置背景为圆角
GradientDrawable drawable = new GradientDrawable();
drawable.setCornerRadius(10);
drawable.setColor(Color.BLUE);
setBackground(drawable);
// 设置字体为自定义字体
Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "custom_font.ttf");
setTypeface(typeface);
}
}
init()メソッドでは GradientDrawable オブジェクトを作成し、setCornerRadius() メソッドで角丸の半径を設定、setColor() メソッドで背景色を設定しています。作成した drawable オブジェクトを setBackground() メソッドで背景に設定しています。
次に、Typefaceクラスを使用してカスタムフォントファイルを読み込み、ボタンのフォントを設定します
最後に、レイアウトファイルでカスタムボタン・コントロールを使用する必要があります。XMLレイアウトファイルでは、完全修飾名を使用してカスタムコントロールを参照できます。
<com.example.myapplication.CustomButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Button" />
これでシンプルなカスタム Button コントロールが完成しました。申請を実行すると、ボタンの背景色が青になり、フォントがカスタムフォントに変更されているのが確認できます。
カスタムフォントを利用する場合は、assetsフォルダにフォントファイルを配置し、コード内で正しいファイルパスを使って読み込む必要があります。