在代码中改变圆角背景,需要给空间设置一个默认的背景,要在xml中定义一个shape,如:
最后在代码中使用
package com.dxx.shapetest;
import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView solid_tv, hollow_tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
solid_tv = (TextView) findViewById(R.id.solid_tv);
shapeSolid(this, solid_tv,0);
hollow_tv = (TextView) findViewById(R.id.hollow_tv);
shapeSolid(this,hollow_tv,1);
}
/**
* 设置圆角的背景
*
* @param context 上下文
* @param v View
*/
public void shapeSolid(Context context, View v, int pos) {
GradientDrawable gd = (GradientDrawable) v.getBackground();
int strokeWidth = 1; // 1dp 边框宽度
int roundRadius = 8; // 8dp 圆角半径
int strokeColor = 0xffff4984;//边框颜色
int fillColor = 0xffffffff;//内部填充颜色
if (pos == 1) {
strokeColor = 0xff02FF13;//边框颜色
fillColor = 0xff02FF13;//内部填充颜色
}
gd.setColor(fillColor);
gd.setCornerRadius(dp2px(context, roundRadius));
gd.setStroke(dp2px(context, strokeWidth), strokeColor);
}
/**
* 根据手机的分辨率dp 转成px(像素)
*/
public int dp2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
最后效果图