1

假设我有这个布局 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 代码工作正常,但我无法找出android:theme="@style/ripplePressedJava 中的等价物。

4

2 回答 2

1

我认为如果您要使用 aContextThemeWrapper来构建您的视图,那么您将使用指定的主题。

Context themedContext = new ContextThemeWrapper(context, R.style.orange_theme);
CustomButton submit = new CustomButton(themedContext);
于 2016-07-19T00:54:50.930 回答
1

你可以使用ContextThemeWrapper

在文档中

于 2016-07-19T00:55:14.690 回答