xml可扩展标记语言写shape文件可以很方便自定义图形,但缺点是其中颜色是写死的。昨日恰好遇到需要使用服务下发的颜色定义view的背景,并且还得是圆角的,最终找到的方式是使用RoundRectShape。
public class MainActivity extends Activity { private int beforeLength = 0, cursor = 0; private int limit = 20; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView test = (TextView) findViewById(R.id.number_of_words); RoundRectShape rr = new RoundRectShape(new float[]{ 60, 60, 60, 60, 60, 60, 60, 60}, null, null); // 60px = 20dp ShapeDrawable drawable = new ShapeDrawable(rr); drawable.getPaint().setColor(Color.RED); //指定填充颜色 drawable.getPaint().setStyle(Paint.Style.FILL); // 指定填充模式 test.setBackgroundDrawable(drawable); } }
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="155dp"> <TextView android:id="@+id/number_of_words" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="10dp" android:background="@color/colorAccent" android:gravity="bottom" android:textColor="#ffffff" android:textSize="14sp" /> </FrameLayout>