假设我有这个布局xml(由于 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>
themes.xml (将波纹颜色设为白色):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="ripplePressed">
<item name="android:colorControlHighlight">@color/White</item>
</style>
</resources>
在Java中模拟xml:
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);
java代码工作正常,但我无法弄清楚Java中的等效android:theme="@style/ripplePressed
。
答案 0 :(得分:1)
我认为如果您使用ContextThemeWrapper
构建视图,那么您将使用指定的主题。
Context themedContext = new ContextThemeWrapper(context, R.style.orange_theme);
CustomButton submit = new CustomButton(themedContext);
答案 1 :(得分:1)
您可以使用ContextThemeWrapper
类