【发布时间】:2021-02-12 13:55:40
【问题描述】:
我创建了一个扩展 EditText 的类,并将它们强制为带边框的方形。我无法单击或编辑其中任何一个中的文本。当我将 4 个 SquareCell 视图更改回 EditText 视图时,我可以编辑它们(但显然会丢失方形格式)。为什么我不能编辑 SquareCell 视图?
SquareCell 类
package com.example.autogrid
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
class SquareCell @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : androidx.appcompat.widget.AppCompatEditText(context, attrs, defStyleAttr) {
private var squareSize = 0f
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.BLACK
style = Paint.Style.STROKE
strokeWidth = 5f
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
//find smaller dimension between width and height and set layout size to it
val smallerDim = Math.min(
MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec)
)
super.onMeasure(
MeasureSpec.makeMeasureSpec(smallerDim, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(smallerDim, MeasureSpec.EXACTLY)
)
squareSize = smallerDim.toFloat()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
//add border
canvas.drawRect(0f, 0f, squareSize, squareSize, paint)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.example.autogrid.SquareCell
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Edit Text 00"/>
<com.example.autogrid.SquareCell
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Edit Text 01"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.example.autogrid.SquareCell
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Edit Text 10"/>
<com.example.autogrid.SquareCell
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Edit Text 11"/>
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
SquareCells 的结果(不可编辑):
我使用 EditTexts 时的结果(可编辑但不是正方形):
【问题讨论】:
-
你看到这个答案stackoverflow.com/a/46393628/11538132了吗?
标签: android kotlin android-edittext