我尝试为我的仪表板活动实现复合视图。它是Button
TextView
。需要我的主题。
我有attr.xml
个文件
<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。你可以通过建议来帮助我吗?
答案 0 :(得分:2)
您需要设置drawable的边界:
topDrawable.setBounds( new Rect( 0, 0, w, h ) );
或者使用:
btn.setCompoundDrawablesWithIntrinsicBounds(null, topDrawable, null, null);