Concatenate a @string and XML text

Asked

Viewed 821 times

1

I have a string called "key" and wanted to add the sequential numbers next to it in some textviews

, but I don’t know how to concatenate into XML. For example:

android:text="@string/key" + "1"
android:text="@string/key" + "2"
android:text="@string/key" + "3"

Someone could give me a light?

  • This is not possible in XML, only in Java/Kotlin.

1 answer

2


That way it’s not possible.

One possible approach is to create a class that inherits from view who intends to use and give you this ability.

Start by declaring an attribute to be used in xml. It will serve to receive the value to concatenate to the value assigned to android:text.

In the folder /res/values create, if not, a file called attrs.xml, with the following content:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ConcatenateTextView">
        <attr name="concatenate" format="string" />
    </declare-styleable>
</resources>

If the file already exists, only include

<declare-styleable name="ConcatenateTextView">
    <attr name="concatenate" format="string" />
</declare-styleable>

The View to inherit must be one that has the attribute android:text, anyone who, directly or indirectly, inherits from Textview.

Example for Textview:

Concatenatetextview.java

public class ConcatenateTextView extends android.support.v7.widget.AppCompatTextView {

    public ConcatenateTextView(Context context) {
        super(context);
    }

    public ConcatenateTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        handleCustomAttributes(context, attrs);
    }

    public ConcatenateTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        handleCustomAttributes(context, attrs);
    }

    private void handleCustomAttributes(Context context, AttributeSet attrs){
        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.ConcatenateTextView,
                0, 0);

        String concatenateText = a.getString(R.styleable.ConcatenateTextView_concatenate);
        if(concatenateText != null){
            setText(getText() + concatenateText);
            a.recycle();
        }
    }
}

Example of use:

<o.seu.name.space.ConcatenateTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/key"
    app:concatenate="1"/>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.