Concatenate an @string and a text in XML

2

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

, but I do not know how to concatenate it in XML. For example:

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

Could someone give me a light?

    
asked by anonymous 01.03.2018 / 23:50

1 answer

3

That way it's not possible.

A possible approach is to create a class that inherits from the view that you want to use and give it that capability.

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

In the / res / values folder, create a file named 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 include it only

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

The View to inherit must be one that has the android:text attribute, any one that, directly, indirectly, inherits from TextView.

TextView example:

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 usage:

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