Middle
How would you extend a TextView using a specific method?
sobes.tech AI
Answer from AI
You can extend TextView by creating your own class that inherits from TextView and overriding the necessary methods, such as onDraw() or onMeasure(). For example:
public class CustomTextView extends androidx.appcompat.widget.AppCompatTextView {
public CustomTextView(Context context) {
super(context);
init();
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// Additional initialization logic if needed
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Add custom drawing logic, for example, a border or underline
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Add custom size measurement logic
int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
// You can modify the measured dimensions if needed
}
}
In this example, the CustomTextView class inherits from AppCompatTextView. The onDraw() method is overridden to add a red border around the text, and onMeasure() remains unchanged but demonstrates the possibility of overriding to customize size measurements.
To use a custom TextView in XML layout, specify the full class name:
<com.your_package_name.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Custom TextView!" />
Replace com.your_package_name with the path to your package.