开头一句话结论——用FlexboxLayout组合布局。
效果图如下:
自定义类:
import android.content.Context import android.util.AttributeSet import androidx.appcompat.widget.AppCompatEditText import androidx.appcompat.widget.AppCompatTextView import androidx.core.content.ContextCompat import com.google.android.flexbox.AlignItems import com.google.android.flexbox.FlexDirection import com.google.android.flexbox.FlexWrap import com.google.android.flexbox.FlexboxLayout class FillBlankLayout : FlexboxLayout { constructor(context: Context) : super(context) { initView() } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { initView() } constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super( context, attrs, defStyle ) { initView() } private fun initView() { flexDirection = FlexDirection.ROW flexWrap = FlexWrap.WRAP alignItems = AlignItems.CENTER } //设置数据 例:大家好:我是<fill>,我来自<fill>。 fun setData(data: String) { removeAllViews() val split = data.split("<fill>") //根据传入的文本 使用<fill>进行切割 split.forEachIndexed { index, s -> val textView = AppCompatTextView(context) textView.setTextColor( ContextCompat.getColor( context.applicationContext, R.color.color_3e4644 ) ) textView.textSize = 14f //textview的文字大小 textView.text = s //设置textview的文字 addView(textView) if (index < split.size - 1) { val editText = AppCompatEditText(context) editText.minWidth = ViewUtil.dp2Px(context.applicationContext, 60) editText.textSize = 14f editText.setTextColor( ContextCompat.getColor( context.applicationContext, R.color.color_3e4644 ) ) addView(editText) } } } //获取用户输入的文字列表 fun getResult(): MutableList<String> { val result = mutableListOf<String>() for (i in 0 until childCount) { val childAt = getChildAt(i) if (childAt is AppCompatEditText) { result.add(childAt.text.toString()) } } return result } }布局代码:
<com.xxx.view.fillblank.FillBlankLayout android:id="@+id/fbl" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/dm_20_dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <androidx.appcompat.widget.AppCompatButton android:id="@+id/btnGet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="@dimen/dm_20_dp" android:text="提取" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/fbl" />activity代码
fbl.setData("大家好,我是<fill>,我来自<fill>。") btnGet.setOnClickListener { val result = fbl.getResult() result.forEach { Timber.e("数据:$it") } }
