Search code examples
javaandroidlayoutandroid-themerippledrawable

Android - What's the equivalent of "android:theme=" in Java?


Let's say i have this layout xml (blue color button with ripple due to selectableItemBackground):

<LinearLayout
    android:id="@+id/yes_frame"
    android:background="@color/Blue"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1">
    <Button
        android:id="@+id/dialogCancelButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Cancel"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/White"
        android:background="?attr/selectableItemBackground"
        android:theme="@style/ripplePressed"
    />
</LinearLayout>

And themes.xml (to make ripple color as white):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="ripplePressed">
        <item name="android:colorControlHighlight">@color/White</item>
    </style>
</resources>

Simulate xml in Java:

    CustomButton submit = new CustomButton(context); 

    LinearLayout wrapperLinearLayout = new LinearLayout(context);
    wrapperLinearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    wrapperLinearLayout.setBackgroundColor(Color.BLUE);
    LinearLayout.LayoutParams layoutParamsButton = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            (int) Utils.convertDpToPixel(55, context));

    //selectableItemBackground in Java
    int[] attrs = new int[]{R.attr.selectableItemBackground};
    TypedArray ta = context.obtainStyledAttributes(attrs);
    int backgroundResource = ta.getResourceId(0, 0);
    submit.setBackgroundResource(backgroundResource);
    ta.recycle();

    submit.setLayoutParams(layoutParamsButton);
    submit.setTextColor(Color.WHITE);
    submit.setText("some text");

    wrapperLinearLayout.addView(submit);

The java code works fine except i can't figure out the equivalent android:theme="@style/ripplePressed in Java.


Solution

  • I think if you were to use a ContextThemeWrapper to construct your view then you would use the specified theme.

    Context themedContext = new ContextThemeWrapper(context, R.style.orange_theme);
    CustomButton submit = new CustomButton(themedContext);