2012-02-10 43 views
0

我嘗試爲我的儀表板活動實施複合視圖。它的ButtonTextView。需要我的主題。 我attr.xml文件declare-styleable drawableTop

<declare-styleable name="DashboardButton"> 
    <attr name="drawableTop" format="reference"/> <!-- i want set android:drawableTop of button--> 
    <attr name="btnText" format="string" /> <!-- text about button functionality--> 
    <attr name="tvText" format="string" /> <!-- additional information --> 
</declare-styleable> 

也有dashboard_button.xml佈局

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" > 

    <Button 
     android:id="@+id/btn" 
     style="@style/DashboardButton" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" /> 

    <TextView 
     style="@style/btn_add_info" 
     android:id="@+id/txtView" 
     android:text="0"/> 
</RelativeLayout> 

也有自定義組件DashboardButton

public class DashboardButton extends RelativeLayout { 

private TextView txtView; 
private Button btn; 

public DashboardButton(Context context) { 
    super(context); 
} 

public DashboardButton(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    LayoutInflater inflater = LayoutInflater.from(context); 
    inflater.inflate(R.layout.dashboard_button, this); 
    loadViews(attrs); 
} 

public DashboardButton(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
    LayoutInflater inflater = LayoutInflater.from(context); 
    inflater.inflate(R.layout.dashboard_button, this); 
    loadViews(attrs); 
} 

private void loadViews(AttributeSet attrs) { 
    txtView = (TextView) findViewById(R.id.txtView); 
    btn = (Button) findViewById(R.id.btn); 
    TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.DashboardButton); 
    txtView.setText(a.getString(R.styleable.DashboardButton_tvText)); 
    btn.setText(a.getString(R.styleable.DashboardButton_btnText)); 
    //i think issue here but can't understand what i should do 
    Drawable topDrawable = a.getDrawable(R.styleable.DashboardButton_drawableTop); 
    btn.setCompoundDrawables(null, topDrawable, null, null); 
    a.recycle(); 
} 

public void setTxtViewText(CharSequence text) { 
    txtView.setText(text); 
} 
} 

最後我有

<my.package.name.DashboardButton 
     android:id="@+id/Btn" 
     style="@style/DashboardButton" 
     app:btnText="@string/my_function" 
     app:tvText="@string/add_info" 
     app:drawableTop="@drawable/function_logo"> 
    </my.package.name.DashboardButton> 

所有的工作正常,除了app:drawableTop drawable不在運行時加載,我沒有看到drawable。你能幫我建議嗎?

回答

2

您需要設置的界限爲您繪製:

topDrawable.setBounds(new Rect(0, 0, w, h)); 

或選擇使用:

btn.setCompoundDrawablesWithIntrinsicBounds(null, topDrawable, null, null); 
相關問題