如何在 Android 的 LinearLayout 中以编程方式在顶部中心绘制一个圆?

How to draw programmatically a circle at top center in LinearLayout in Android?

我已经知道如何在 Android 中使用 Canvas 画一个圆,但我想把它恰好放在我的线性布局的中间顶部。

尝试使用以下代码,它会在屏幕中央绘制圆圈。

//Activity xml
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

 <com.nec.sampleapp.CircleView
    android:id="@+id/circle_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</LinearLayout>


 //Activity Code
 class TestActivity : AppCompatActivity() { 
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_test)
}
}


// This is Circle view class
class CircleView(context: Context, attributeSet: AttributeSet) : 
View(context, attributeSet) {
private var paint = Paint()
private var r = 255
private var g = 0
private var b = 0

//Circle radius
private var radius = 90F

// screen x point
private var sX: Int = 0

// screen y point
private var sY: Int = 0

init {
    paint.setARGB(255, r, g, b)
    sX = (Resources.getSystem().displayMetrics.widthPixels) / 2
    sY = (Resources.getSystem().displayMetrics.heightPixels) / 2
}

override fun onDraw(canvas: Canvas?) {
    canvas?.drawCircle(sX.toFloat(), 100F, radius, paint)
}
}