[英]How to set text color as link?
我有textview,當我聚焦或像鏈接文本一樣傾斜顏色時,我想改變顏色,我嘗試按照此方法進行操作,但仍然無法正常工作
請幫助,謝謝
這是我的Java代碼
public class TextColorActivity extends Activity {
/** Called when the activity is first created. */
ColorStateList cl = null;
private TextView title;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
title = (TextView)findViewById(R.id.hello);
try {
Log.d("test","try");
XmlResourceParser xpp = getResources().getXml(R.drawable.selector_txt);
cl = ColorStateList.createFromXml(getResources(), xpp);
} catch (Exception e) {}
title.setTextColor(cl);
title.setFocusable(true);
title.setClickable(true);
title.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("test","click");
}
});
}
這是我的選擇器_txt.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:color="@color/Darkgoldenrod"/>
<item android:state_pressed="true" android:state_enabled="false"
android:color="@color/Darkgreen" />
<item android:state_enabled="false" android:color="@color/Red" />
<item android:color="@color/blue"/>
這是我的main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/hello"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textSize="30dp"
android:textStyle="bold"
android:duplicateParentState="true"/>
如果需要,還可以在xml中設置顏色。 只需在res文件夾中創建一個顏色文件夾並將xml文件移動到那里,然后您就可以通過android:textColor="@color/selector_txt"
關於您遇到的問題。 Android將始終使用選擇器中的第一個匹配項。 如果按下TextView,它也會被聚焦。 因此,將android:pressed="false"
到您的第一個項目中,或者將其移動到按下狀態行之后。
這是完整的xml:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_enabled="false" android:color="@color/Red" /> <item android:state_pressed="true" android:color="@color/Darkgreen" /> <item android:state_focused="true" android:color="@color/Darkgoldenrod"/> <item android:color="@color/blue"/> </selector>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.