2016-06-28 103 views
0

我試圖將可繪製背景設置爲以編程方式創建的按鈕。以編程方式爲編程創建的按鈕設置可繪製背景

下面是我創建按鈕和設置背景

Button increaseQuantity = new Button(this); 
increaseQuantity.setText("+"); 
//increaseQuantity.setBackgroundResource(R.drawable.quantity_button); 
increaseQuantity.setBackgroundDrawable(getResources().getDrawable(R.drawable.quantity_button)); 

下面的代碼是其對於繪製

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" > 
<stroke android:width="1dp" android:color="#ee404040" /> 
<size android:width="2dp" android:height="2dp"/> 
<gradient android:startColor="#11809100" android:centerColor="#11910000" android:endColor="#55FFB900" android:angle="45" /> 
</shape> 

代碼中的XML作爲按照XML我的按鈕應該是圓形(因爲寬度和高度是相同的),但我無法得到一個圓形的按鈕,而是我得到一個橢圓形的按鈕。任何人都可以更正此代碼來獲得圓形按鈕?

回答

0

只是兩件事情在這裏:

  1. 更換過時方法:setBackgroundDrawablegetDrawable已被棄用。
  2. 設置尺寸編程

這應該做的工作:

increaseQuantity.setBackground(ContextCompat.getDrawable(this, R.drawable.round)); 
increaseQuantity.setLayoutParams(new LinearLayout.LayoutParams(100, 100)); 
//replace 100 with your desired diameter of the button. 

此外,你將不得不更換LinearLayout給你你的按鈕與關聯父佈局。

+0

我使用表格佈局來放置這個按鈕,它會爲表格佈局工作嗎? – Suresh

+0

是的,它應該工作。只需使用'新的TableLayout.LayoutParams(100,100)'代替'LinearLayout.LayoutParams(100,100)' –

相關問題