CustomView (in frameLayout)
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val customView = CustomView(this, "This is my view")
binding.frameLayout.addView(customView)
}
}
class CustomView(context: Context, private val text: String): View(context) {
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
val paint = Paint()
paint.color = Color.BLACK
paint.textSize = 100f
canvas?.drawText(text, 0f, 100f, 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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginTop="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent">
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Custom Widget (모름)
CustomText.kt
class CustomText: AppCompatTextView {
fun process(delimiter: String) {
var one = text.substring(0, 4)
var two = text.substring(4, 6)
var three = text.substring(6)
text = "$one $delimiter $two $delimiter $three"
}
constructor(context: Context): super(context) { }
constructor(context: Context, attrs:AttributeSet): super(context, attrs) {
val typed = context.obtainStyledAttributes(attrs, R.styleable.CustomText)
val size = typed.indexCount
for (i in 0 until size) {
when (typed.getIndex(i)) {
R.styleable.CustomText_delimiter -> {
val delimiter = typed.getString(typed.getIndex(i)) ?: "-"
process(delimiter)
}
}
}
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int): super(context, attrs, defStyleAttr) { }
}
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomText">
<attr name="delimiter" format="string" />
</declare-styleable>
</resources>