0

Is it possible to apply attributes of one view that is defined via xml to other view that is creating programmatically?

In my case situation is next -

There is custom view FormField:

class FormField extends LinearLayout {
    ...
    @Override
    protected void onFinishInflate() {
       super.onFinishInflate();
       final int childCount = getChildCount();
       if (childCount > 1) {
          throw new IllegalStateException("FormField can store only one child view");
       }
       labelView = new TextView(getContext());
       addView(labelView, 0);
    }

with next target usage:

<com.korovyansk.android.views.FormField
    style="@style/Label"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Field label"
    android:layout_marginBottom="300dp"
    android:layout_marginRight="16dp"
    android:layout_marginLeft="16dp">

    <com.korovyansk.android.views.EditText
        style="@style/TextField"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapSentences"
        android:imeOptions="actionNext"/>

</com.korovyansk.android.views.FormField>

So the idea is to transfer attributes (style, text, margins) from FormField to TextView created dynamically in onFinishInflated method.

AlexKorovyansky
  • 4,873
  • 5
  • 37
  • 48
  • In the constructor of `FormField` you get the attributes of the view and you could then, later, apply them to the `TextView`. – user Jul 09 '14 at 08:40
  • @Luksprog I tried it, it works good for layout_margin* parameters, but doesn't work for text, not sure about style. – AlexKorovyansky Jul 09 '14 at 08:46
  • How do you try to get the text attribute? `context.obtainStyledAttributes()` should allow you to get the text. – user Jul 09 '14 at 09:05
  • @Luksprog I tried to save AttributeSet that are passed to constructor of TextField, and later construct TextView with TextView(Context, AttributeSet) constructor. – AlexKorovyansky Jul 09 '14 at 09:09
  • Looks like somewhere parameters are filtered, but I cannot find exact place in the source of Android. – AlexKorovyansky Jul 09 '14 at 09:21
  • I was able to solve my concrete case using http://stackoverflow.com/questions/18013971/how-to-use-standard-attribute-androidtext-in-my-custom-view, but as side effect I noticed a bit of magic - http://stackoverflow.com/questions/24650879/magic-with-obtainstyledattributes-method – AlexKorovyansky Jul 09 '14 at 10:20

0 Answers0