【问题标题】:Android - What's the equivalent of "android:theme=" in Java?Android - Java 中“android:theme=”的等价物是什么?
【发布时间】:2016-07-19 00:49:41
【问题描述】:

假设我有这个布局 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

【问题讨论】:

    标签: java android layout android-theme rippledrawable


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你可以使用ContextThemeWrapper

      In docs

      【讨论】:

        猜你喜欢
        • 2013-03-12
        • 1970-01-01
        • 2021-12-03
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 2021-10-18
        相关资源
        最近更新 更多