How to change the value of a custom attribute?

1.2k views Asked by At

I can change value of a TextView's "android:text" attribute easily:

    textTem = (TextView) findViewById(R.id.textTem);
    textTem.setText("ssss");

But I have a custom component with custom attribute.

my custom component class:

        public class DayItem extends RelativeLayout {
            ...
        }

my custom component in xml:

        <com.example.a28210.weathpredict.DayItem
            android:id="@+id/days1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            item:dayweather="snow"
            item:daymaxtem="-2°"
            item:daymintem="-12°"
            item:daydate="12.8" />

my custom attribute:

            <?xml version="1.0" encoding="utf-8"?>
            <resources>
                <declare-styleable name="DayItem">
                    <attr name="daydate" format="string" />
                    <attr name="dayweather" format="string" />
                    <attr name="daymaxtem" format="string" />
                    <attr name="daymintem" format="string" />
                </declare-styleable>
            </resources>

My question is:There is no method to change the value of a custom attribute.
How should I do if I want to change the value of acustom attribute?

                    DayItem d=(DayItem)view.findViewById(R.id.days1);
                    d.     //?????
1

There are 1 answers

0
Sua Le On

Change value of view use custom attribute, not change value of custom attribute.

Custom attribute use to pass a value from XML to use in your custom view. For example:

someView.text = getString(R.styleable.DayItem_dayweather) //return "snow"

Now you want to change value of someView from runtime, just add a method to your custom view :

   public class DayItem extends RelativeLayout {                
      ...
      void setWeather(String value){
        someView.text = value
      }
      ...

    }

then you can

DayItem d = (DayItem)view.findViewById(R.id.days1);
d.setWeather("Sunny")  

Hope this helps you.