I have three Material text views, I want to change the background color of the text view according to the text view shape. I tried multiple options but it goes outside of text view shape. I have round corners text view but color fill like a simple rectangle.
<com.google.android.material.textview.MaterialTextView
android:id="@+id/textViewLoseWeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="65dp"
android:text="Lose Weight"
android:textColor="@color/purple_500"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textViewGoals"
tools:ignore="MissingConstraints" />
<com.google.android.material.textview.MaterialTextView
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_marginTop="4dp"
android:id="@+id/textViewLoseWeightSubtitle"
android:background="@drawable/textview_outline_style"
android:paddingStart="16dp"
android:paddingTop="16dp"
android:text="Get leaner and improve Your fitness"
android:textColor="@color/purple_500"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textViewLoseWeight" />
//.java
View.OnClickListener listener = new View.OnClickListener() {
@SuppressLint("NonConstantResourceId")
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.textViewLoseWeightSubtitle:
mLoseWgt.setBackgroundColor(Color.parseColor("#363C60"));
mLoseWgt.setTextColor(Color.WHITE);
after clicking on the text view, it changes like above. I want background color inside round corner shape like the original text view have
You define your TextView
and also it's android:background
attribute:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get leaner and improve Your fitness"
android:background="@drawable/round_fill_color"
android:layout_centerInParent="true"
android:textColor="#ffffff"
android:padding="10dp"/>
</RelativeLayout>
And here the mentioned attribute in a new drawable
called round_fill_color.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#363c60"/>
<stroke android:width="3dp" android:color="#ffffff" />
<corners android:radius="30dp"/>
<padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
</shape>
That is the suggested way to make custom attributes for single widgets
.
If you want to define one layout
for all I recommend to do that over styles.xml
and themes
.
The result: