2017-08-28 29 views
1

如何獲取參考顏色的實際值?在佈局我可以使用下面的...如何以編程方式獲取colorAccent等內置資源的價值?

android:textColor="?android:attr/colorAccent" 

..和這部作品中設置一個TextView的主題定義強調色的文本顏色。如何在運行時獲得使用colorAccent代碼的價值?

此外,你如何發現所有可用值的列表,必須有一長串可用的顏色列表,我可以找到,但列表定義在哪裏?

回答

1

如果資源是一個Android定義之一:

var id = Android.Resource.Attribute.ColorAccent; 

如果資源是一個對話框,窗口小部件等內..這不是一個Android系統資源(即,得到DatePickerDialog資源)

var id = SomeDatePickerDialog.Resources.GetIdentifier("date_picker_header_date", "id", "android"); 

使用得到的ID:

var typedArray = Theme.ObtainStyledAttributes(new int[] { id }); 
    var color = typedArray.GetColor(0, int.MaxValue); 
    if (color != int.MaxValue) 
    { 
     Log.Debug("COLOR", color.ToString()); 
    } 

與API /主題的R名單的變化,可用的基礎值:

但你必須使用Android源的API的完整參考你正在看:

在奧利奧測試中定義的顏色一般:

然後查看特定顏色xml文件中的定義方式,並使用該定義查找其實際值(在valueXXX文件中的一箇中)....

2

對於例如,你有你可以得到價值的東西是這樣的:

//default color instead the attribute is not set. 
var color = Color.Blue; 

var attributes = new int[] { Android.Resource.Attribute.ColorAccent }; 
var typeArray = ObtainStyledAttributes(attributes); 

//get the fist item (we are sending only one) and passing 
//the default value we want, just in case. 
var colorAccent = typeArray.GetColor(0, color); 

colorAccent將有Color集的主題爲ColorAccent屬性,如果任何或默認值。

重要的問題是該方法ObtainStyledAttributesContext的一部分,所以如果你已經在一個活動中,你會發現它作爲它的一部分,但如果你在其他任何類,你將需要在情況背景下通過它不可用。

有關可用值的完整列表,您可以從Android.Resource.Attribute類中獲得。在VS做一個檢查,看看這個類有不同的屬性。也許Android文檔有更好的方法。

希望這helps.-

相關問題