Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Android attributes on my custom view

I have created a custom layout class (extends RelativeLayout) and have a TextView as part of the layout.

I want to apply the properties declared in XML to my TextView, is there anyway I can read the android attributes (not my custom attributes, that part is already taken care of).

For example in my XML I'll have this:

<my.custom.MyLayout
    android:layout_width="100dp"
    android:layout_height="20dp"
    android:text="SomeText" /> 

I want to read the text attribute and apply it to my TextView (currently it is being applied to the RelativeLayout) instead of creating my own attribute and reading it.

My custom layout is something like this :

public class MyLayout extends RelativeLayout {

    private TextView textView;
    public void MyLayout(final Context context, final AttributeSet attrs) {
        /**Read android attributes and apply it to TextView **/
        ??
    }

My current solution is creating custom attributes and reading them, but I feel that is not a good solution as I'll be duplicating every attribute declared to TextView.

More info about my current solution.

I have a custom attribute called myText which I use to apply the text declared in XML to my TextView.

In my layout XML :

myNameSpace:myText="SomeText"

And read it in my Java class :

String text= a.getString(R.styleable.MyStyleable_myText);
textView.setText(text);

I'm looking to get rid of my custom attributes and read "android:" attributes.

like image 935
AkasH Avatar asked Oct 16 '15 05:10

AkasH


1 Answers

First of all I am not sure if setting android:text will be possible for view extending RelativeLayout. If it is possible do it like in TextView implementation:

final Resources.Theme theme = context.getTheme();
a = theme.obtainStyledAttributes(attrs, com.android.internal.R.styleable.TextView, defStyleAttr, defStyleRes);
text = a.getText(attr);

So basically it's the same way you get your custom properties but with different styleable.

If it's not working I would consider another approach. I did it for one of my custom views. Since you have a TextView in your custom view you could create it in XML and then get a reference to that child inside your custom view.

<YourCustomView>
    <TextView android:text="someText"/>
<YourCustomView/>
like image 113
Damian Petla Avatar answered Oct 05 '22 08:10

Damian Petla