我有一个 android 应用程序,它有一个按钮,我想在它被禁用时有黑色文本和背景,然后在启用时有白色书写的绿色背景。
我已经启用和禁用工作,但如果我更改颜色,无论其状态如何,按钮都会保持不变。
我读过我需要使用自定义选择器来手动设置颜色,这就是我到目前为止所得到的:
res/drawable 中的 continuebutton.xml:(绿色在 /res/values/colors.xml 中声明)
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_enabled="false"
android.textColor ="@android:color/black"
android:drawable="@android:color/black" />
<item
android:state_enabled="true"
android.textColor ="@android:color/white"
android:drawable="@color/green" />
Run Code Online (Sandbox Code Playgroud)
布局 xml 文件中的继续按钮:
android:id="@+id/continueButton"
android:layout_width="200dp"
android:layout_height="55dp" android:layout_gravity="center" android:paddingTop="10dp" android:textSize="18dp"
android:text="@string/continueButton" android:background="@drawable/continuebutton" />
Run Code Online (Sandbox Code Playgroud)
我想我在 continuebutton.xml 文件中做错了什么,但我不知道如何修复它。
任何帮助将不胜感激!
谢谢
更新:
我有背景改变颜色,最后一个问题是解决的是无论按钮是禁用还是启用,文本颜色都保持黑色(启用时应该是白色)。
我是否需要在 res/drawable 中为文本颜色创建一个新的 xml 文件?
有任何想法吗?
删除属性
android:src="@drawable/continuebutton"
Run Code Online (Sandbox Code Playgroud)
并使用
android:background="@drawable/continuebutton"
Run Code Online (Sandbox Code Playgroud)
在运行时你可以通过以下方式更改背景图像
myButton.setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.myfirstbg));
myButton.setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.mysecondbg));
Run Code Online (Sandbox Code Playgroud)
如果你想使用背景颜色删除这两个属性`
android:src="@drawable/continuebutton"
android:background="@drawable/continuebutton"
Run Code Online (Sandbox Code Playgroud)
并使用它更改背景颜色
myButton.setBackgroundColor(Color.BLUE);
myButton.setBackgroundColor(Color.GREEN);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12117 次 |
| 最近记录: |