实际开发中常用3个节点:corners(圆角)、solid(填充)和stroke(描边)。
MainActivity
package com.example.junior;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
public class ShapeActivity extends AppCompatActivity implements View.OnClickListener {
private View v_content; // 声明一个视图对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shape);
// 从布局文件中获取名叫v_content的视图
v_content = findViewById(R.id.v_content);
// 给btn_rect设置点击监听器
findViewById(R.id.btn_rect).setOnClickListener(this);
// 给btn_oval设置点击监听器
findViewById(R.id.btn_oval).setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_rect) { // 点击了按钮btn_rect
// 把矩形形状设置为v_content的背景
v_content.setBackgroundResource(R.drawable.shape_rect_gold);
} else if (v.getId() == R.id.btn_oval) { // 点击了按钮btn_oval
// 把椭圆形状设置为v_content的背景
v_content.setBackgroundResource(R.drawable.shape_oval_rose);
}
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:id="@+id/v_content"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_margin="20dp" />
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:background="#000000"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btn_rect"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="圆角矩形背景"
android:textColor="#000000"
android:textSize="17sp" />
<Button
android:id="@+id/btn_oval"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="椭圆背景"
android:textColor="#000000"
android:textSize="17sp" />
</LinearLayout>
</LinearLayout>
shape_rect_gold
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- 指定了形状内部的填充颜色 -->
<solid android:color="#ffdd66" />
<!-- 指定了形状边线的粗细与颜色 -->
<stroke
android:width="1dp"
android:color="#ffaaaaaa" />
<!-- 指定了形状四个圆角的半径 -->
<corners
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp" />
</shape>
shape_oval_rose
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#ff66aa" />
<stroke
android:width="1dp"
android:color="#ffaaaaaa" />
</shape>
result