如何在Appcelerator Titanium中移除Android TextField多余下划线?
解决Titanium SDK 7.0.2.GA Android TextField移除下划线的问题
我之前在使用Titanium 7.x版本开发Android应用时,也碰到过这个头疼的问题——确实没有underlineColorAndroid这类直接控制下划线的属性。不过折腾了一阵后,找到了几个实用的解决方案,分享给你:
方法1:自定义背景Drawable替换下划线
这是最常用的方式,通过自定义Android的Drawable文件来覆盖默认的下划线样式:
- 在你的项目目录
app/platform/android/res/drawable下创建一个新的XML文件,比如命名为textfield_clear_underline.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 焦点状态下的背景 --> <item android:state_focused="true" android:drawable="@android:color/transparent" /> <!-- 默认状态下的背景 --> <item android:drawable="@android:color/transparent" /> </selector>
- 在创建TextField时,将
backgroundImage设置为这个自定义Drawable:
var myTextField = Ti.UI.createTextField({ hintText: "请输入内容", width: '80%', height: 40, backgroundImage: "/drawable/textfield_clear_underline.xml" });
如果需要在焦点状态下显示自定义边框,只需要修改Drawable里对应状态的android:drawable值即可。
方法2:直接操作原生Android控件
Titanium的TextField对应原生Android的EditText,我们可以通过androidView属性获取原生控件,然后直接修改其背景:
var myTextField = Ti.UI.createTextField({ hintText: "请输入内容", width: '80%', height: 40 }); if (Ti.Platform.osname === 'android') { // 等待控件完成布局后再操作原生视图 myTextField.addEventListener('postlayout', function() { var nativeEditText = myTextField.androidView; // 移除默认背景(包含下划线) nativeEditText.setBackground(null); // 也可以设置透明背景 // nativeEditText.setBackgroundColor(android.graphics.Color.TRANSPARENT); }); }
这个方法的好处是不需要额外创建资源文件,直接通过代码动态修改,适合临时处理单个TextField的场景。
方法3:全局修改主题(统一应用内所有TextField样式)
如果你的应用需要所有TextField都去掉下划线,可以修改Android的主题配置:
- 打开
app/platform/android/res/values/styles.xml文件,在你的应用主题中添加android:editTextStyle属性,指向自定义的EditText样式:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- 其他主题属性 --> <item name="android:editTextStyle">@style/CustomEditTextStyle</item> </style> <!-- 自定义EditText样式 --> <style name="CustomEditTextStyle" parent="Widget.AppCompat.EditText"> <item name="android:background">@android:color/transparent</item> </style>
这样应用内所有使用该主题的TextField都会自动去掉下划线,适合需要统一风格的场景。
内容的提问来源于stack exchange,提问作者Deepak Verma
相关产品推荐
相关产品推荐

