2016-06-28 70 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)' –

相关问题