<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/ImageButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawablePadding="-15sp"
android:drawableTop="@drawable/ic_launcher"
android:paddingTop="32sp"
android:text="this is text"
android:textColor="@color/Black" >
</Button>
这是我为我的XML编写的代码,我一直无法动态创建它,我只需要知道创建此按钮的代码是什么样的。提前谢谢。
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
for (int i = 0; i < 10; i++) {
Button btn = new Button(this);
btn.setLayoutParams(params);
btn.setPadding(0, 32, 0, 0);
btn.setText("MyButton");
btn.setTextColor(color.Green);
Drawable image = Drawable.createFromPath("@drawable/ic_launcher"); //
// btn.setBackgroundDrawable(image);
btn.setCompoundDrawables(null, image, null, null);
btn.setCompoundDrawablePadding(15);
// btn.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
ObjectLayout.addView(btn);
}
这就是我拥有的,但是仍然不一样不确定为什么我不能让它填补它。
答案 0 :(得分:1)
如果要在Drawable
上填充,则必须为Drawable
本身设置Drawable
的背景填充。
setPadding(...)
使用像素代替sp
。
Button myButton = new Button(/* your context, probably "this" */);
myButton.setLayoutParams(
new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
myButton.setPadding(0, 32, 0, 0);
myButton.setText("this is a test");
myButton.setTextColor(android.R.color.black);
myButton.setBackgroundResource(R.id.ic_launcher);