
環境:Android Studio 2.2.1, API 19
今回はXMLではなくコードで設定を行います。
AndroidでViewの背景色のグラデーションと角丸はGradientDrawableを使って定義します。
背景色のグラデーションを設定する場合は、GradientDrawableの引数にグラデーションに使用する色を配列で設定し、Orientationでグラデーションの方向を定義します。
GradientDrawable gradient = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{Color.BLUE, Color.WHITE});
角丸の定義はGradientDrawableのsetCornerRadiusで行います。
最後にGradientDrawableをViewのsetBackgroundで設定します。
private Button buttonSample = new Button(this);
buttonSample.setBackground(gradient);
[サンプルコード全文]
package net.studioks.sample1;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RelativeLayout;
public class sample1 extends Activity {
private Button buttonSample;
@Override
public void onCreate(Bundle bundle){
super.onCreate(bundle);
RelativeLayout relativeLayout = new RelativeLayout(this);
setContentView(relativeLayout);
buttonSample = new Button(this);
buttonSample.setText("Sample");
buttonSample.setTextColor(Color.WHITE);
buttonSample.setPadding(0,0,0,0);
GradientDrawable gradient = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{Color.BLUE, Color.WHITE});
gradient.setCornerRadius(5);
buttonSample.setBackground(gradient);
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(100, 50);
param.leftMargin = 20;
param.topMargin = 10;
param.addRule(RelativeLayout.ALIGN_TOP);
relativeLayout.addView(buttonSample,param);
}
}
Write a comment