【问题标题】:How to write this xml code in android studio?如何在android studio中编写这个xml代码?
【发布时间】:2020-01-22 03:55:07
【问题描述】:

我对 Android Studio 很陌生。作为初学者,我创建了一个简单的应用程序,其中包含“res/drawable”文件夹中的 custom_button.xml 文件。

custom_button.xml 代码:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<shape android:shape="oval">
<solid android:color="@color/colorDarkGrey"/> <!-- default color -->
</shape>
</item>
</selector>

和activity_main.xml文件有两个自定义按钮

activity_main.xml 代码:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity"
android:background="@color/colorWhite">

<Button
        android:id="@+id/MyButton1"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:text="@string/1"
        android:background="@drawable/my_button"/>
<Button
        android:id="@+id/MyButton2"
        android:layout_width="102dp"
        android:layout_height="102dp"
        android:text="@string/2"
        android:background="@drawable/my_button"/>  <!-- How to change default color ? -->

</LinearLayout>

所以我的问题是如何使用 custom_button.xml 文件更改 MyButton2(按钮 ID)默认背景颜色。 我知道我可以再创建一个可绘制的 xml 文件来更改 MyButton2 颜色,但我想使用 custom_button.xml 文件来更改默认颜色。 请大家帮帮我!!!!!!

【问题讨论】:

    标签: android-studio android-layout android-styles android-studio-2.3


    【解决方案1】:

    你可以试试这个代码

         android:backgroundTint="@color/colorPrimary"
    

    在您要更改的按钮中

    【讨论】:

      【解决方案2】:

      这将动态改变背景可绘制颜色。

      这样设置背景颜色

      setBackground(MyButton1,Color.BLUE); // you can set any color here
      setBackground(MyButton2,Color.GREEN);
      
      private void setBackground(View view,int color) {
          Drawable defaultDrawable = AppCompatResources.getDrawable(YourActivity.this, R.drawable.custom_button);
          Drawable wrapDrawable = DrawableCompat.wrap(defaultDrawable);
          DrawableCompat.setTint(wrapDrawable,color);
          view.setBackground(wrapDrawable);
      }
      

      【讨论】:

        【解决方案3】:

        试试这个。我以编程方式创建了形状。例如:

         GradientDrawable shape = new GradientDrawable();
                shape.setShape(GradientDrawable.RECTANGLE);
                shape.setColor(android.graphics.Color.parseColor("#eeeeee"));
                shape.setStroke(4, android.graphics.Color.parseColor("#111111"));
                shape.setCornerRadius(50);
                btnCac.setBackground(shape);
        

        【讨论】:

          猜你喜欢
          • 2016-03-08
          • 2017-02-01
          • 2015-03-30
          • 1970-01-01
          • 1970-01-01
          • 2020-09-07
          • 1970-01-01
          • 1970-01-01
          • 2015-07-28
          相关资源
          最近更新 更多