2012-08-16 20 views
0
<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> 

代碼與純代碼設置爲myButton,XML是這

這是代碼我有我的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

究竟是什麼問題?你能否向我們展示例子?不是很瞭解你的問題。 – prolink007 2012-08-17 13:15:41

回答

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);