2013-10-24 39 views
1

更新 - 請在最後看到一個解決方案,我現在需要的只是一個解釋。 儘管搜索我無法找到同樣的問題檢索屬性的問題

我創建一個自定義Viewpager和定義在attrs.xml

的自定義屬性在視圖尋呼機構造,當我嘗試和檢索屬性我不能讓一個有意義的值。我試過使用

abstract int  getAttributeIntValue(String namespace, String attribute, int defaultValue) 

返回'屬性'的整數值。

public MyViewPager(Context context, AttributeSet attrs) { 
    Log.d(Constant.TAG, "ViewPagerType:" + attrs.getAttributeUnsignedIntValue("http://schemas.android.com/apk/res-auto","view_pager_type",9)); 
    Log.d(Constant.TAG, "ViewPagerType:" + attrs.getAttributeIntValue("http://schemas.android.com/apk/res-auto","view_pager_type",9)); 
    Log.d(Constant.TAG, "ViewPagerType:" + attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","view_pager_type")); 
    Log.d(Constant.TAG, "ViewPagerType:" + attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","garbage")); 

正如你可以看到attrs.getAttributeValue做了一個字符串,但它是沒有意義的我。

這是從日誌報表輸出 - 9如果沒有找到默認的,我不undertand的@ 213號是什麼

ViewPagerType:9   
ViewPagerType:9   
ViewPagerType:@2131230723 
ViewPagerType:null  

這是我attrs.xml

<resources> 
    <declare-styleable name="AutoResizeTextView"> 
     <attr name="ttf_name" format="string"/> 
    </declare-styleable> 
    <declare-styleable name="ViewPagerType"> 
     <attr name="view_pager_type" format="integer"/> 
    </declare-styleable> 
</resources> 

這是我的佈局

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
android:orientation="horizontal" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 


<org.rh.ellierides.MyViewPager xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/textPager" 
    app:view_pager_type="@integer/text_viewpager" 
    android:orientation="horizontal" 
    android:layout_width="0dp" 
    android:layout_height="match_parent" 
    android:layout_weight="24" 
    tools:context=".Main"> 

這是integer.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <integer name="text_viewpager">1</integer> 
    <integer name="image_viewpager">2</integer> 
</resources> 

我想我會創建兩個獨立的視圖頁面,但我仍然想了解這一點。


更新我發現了一個決議,但不明白爲什麼第一個沒有工作,所以請還回答

TypedArray a = null; 
    try { 
     a = getContext().obtainStyledAttributes(attrs, R.styleable.ViewPagerType); 
     int viewpagerType = a.getInt(R.styleable.ViewPagerType_view_pager_type, 9); 
     Log.d(Constant.TAG, "viewpagerType:" + viewpagerType); 
    } finally { 
     if (a != null) { 
      a.recycle(); // ensure this is always called 
     } 
    } 

回答

0

下運作,但正如我上面所說,請解釋給我聽。什麼是傳遞給構造函數的attrs?

TypedArray a = null; 
    try { 
     a = getContext().obtainStyledAttributes(attrs, R.styleable.ViewPagerType); 
     int viewpagerType = a.getInt(R.styleable.ViewPagerType_view_pager_type, 9); 
     Log.d(Constant.TAG, "viewpagerType:" + viewpagerType); 
    } finally { 
     if (a != null) { 
      a.recycle(); // ensure this is always called 
     } 
    }