android 动态修改EditText光标颜色

来源:互联网 发布:小米手机全系列 知乎 编辑:程序博客网 时间:2024/04/28 13:22
    由于有的情况下需要动态添加EditText,这个时候需要修改光标颜色,但是android并没有提供修改光标颜色的方法,仅仅有一个控制是否显示光标。下面的方法可以通过代码修改光标的颜色。
public class TestColorActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        final LinearLayout layout2=new LinearLayout(this);        layout2.setOrientation(LinearLayout.VERTICAL);        Button btn1=new Button(this);        setContentView(layout2);        Button btn2=new Button(this);        btn1.setText("Button1");        btn2.setText("Button2");        layout2.addView(btn1);        layout2.addView(btn2);        EditText editText = new EditText(this);        editText.setText("texttest");        try {            Field f = TextView.class.getDeclaredField("mCursorDrawableRes");            f.setAccessible(true);            f.set(editText, R.drawable.cursor);        } catch (Exception e) {            e.printStackTrace();        }        layout2.addView(editText);        setContentView(layout2);    }}
R.drawable.cursor为自定义的drawable文件:
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle" >    <solid android:color="#FF0000" />    <size android:width="1dp" /></shape>



0 0
原创粉丝点击