如何在程序代码中更改EditText的边框线颜色?

3
实际上我有两个问题。
  1. 如何更改EditText边框线的颜色和大小? 其他答案,如使用shape.xml描述矩形的详细信息并将EditText的android:background设置为@drawable/shape,对我无效,因为我还需要更改聚焦光标的颜色。 我尝试使用styles.xml,并将colorAccent设置为线条颜色,并将EditText的android:theme设置为此。它可以用于颜色,但我无法弄清楚如何在style.xml中更改线条大小。

  2. 我想在运行时更改EditText的颜色,如何在程序代码中更改EditText线的颜色和聚焦光标颜色?

enter image description here

非常感谢任何帮助!我想将白色线条大小更改为1 dp。


文本行的大小取决于EditText的宽度。我们无法动态更改它。 - Sharath
你的意思是我可以改变EditText的android:layout_width属性,边框线就会变细?但我需要将大小设置为固定数字,比如1dp。 - shaoping wang
2个回答

2
你可以使用:
对于API级别为21>21
ColorStateList colorStateList = ColorStateList.valueOf(ContextCompat.getColor(this,R.color.red));
editText.setBackgroundTintList(colorStateList);

对于API级别< 21

editText.getBackground().mutate().setColorFilter(ContextCompat.getColor(this,R.color.red), PorterDuff.Mode.SRC_ATOP);

android:textCursorDrawable 属性设置为 @null,可以使光标的颜色与应用于 EditText 的文本颜色相同。

对于边界线:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">
<stroke
    android:width="1dp"
    android:color="#9ba3af"
    />
</shape>

非常感谢Piyush,我想我已经解决了颜色问题,你知道如何为EditText设置1dp的边框线吗? - shaoping wang
矩形边框线?@shaopingwang - Piyush
@shaopingwang 不需要添加边框。这是EditText的背景色。如果你仍然想要那种边框,那么将EditText的背景设置为透明,并在EditText下方添加一个高度为1dp的View,这样就可以得到所需的EditText了。 - Piyush
嗨,Piyush。很抱歉再次打扰你,我在我的EditView下面有一个textView,如果我设置padding bottom并使边框线向下移动以避免交叉提示消息,EditText和TextView之间的间隙会变大。你知道为什么吗? - shaoping wang
我无法成功地在stackoverflow上上传我的代码,所以我将xml文件通过电子邮件发送给您,地址为piyush.gupta569@gmail.com - shaoping wang
显示剩余3条评论

0
editText.getBackground().mutate().setColorFilter(getResources().getColor(R.color.AppColor), PorterDuff.Mode.SRC_ATOP);

同时,将android:textCursorDrawable属性设置为@null应该会使用android:textColor作为光标颜色。

在您的Java类中使用此代码。


非常感谢你,Arpan!我尝试了你的建议,将android:textCursorDrawable属性设置为@null可以使光标变得更细,并且它的颜色也改变了。SetColorFilter还可以成功地改变边框线的颜色。我想现在我只需要解决线条大小的设置问题 :) - shaoping wang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接