Reputation: 4267
I have a method that creates dynamically an array of Button
for(int i = 0; i < 10; i++){
Button button = new Button(activity);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(200, 100);
button.setLayoutParams(lparams);
button.setTag(0);
buttonArray[i] = button;
layout.addView(button);
}
I created a drawable
(d.xml) that I have to apply to the buttons
<?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="#FFFFFF"/>
</shape>
What I'm not able to do is to apply d.xml to the buttons that I create dynamically.
Can somebody help me? Thank you in advance.
Upvotes: 0
Views: 380
Reputation: 5737
Once you have created your background drawable, you can apply this to the dynamically generated Button in your code.
If your minimum build is API 21 (Lollipop), then use
button.setBackground(activity.getDrawable(R.drawable.d)
You can also use setBackgroundDrawable
for lower APIs.
A more suitable solution can be to use
button.setBackgroundResouce(R.drawable.d)
Give those a go!
Upvotes: 1
Reputation: 1616
in your for loop, after button.setTag(0);
do this button.setBackground(ContextCompat.getDrawable(this, R.drawable.d));
Upvotes: 1
Reputation: 791
Use
button.setBackgroundResource(R.drawable.your_resource);
Upvotes: 1
Reputation: 1272
Use set background resource of Button :
for(int i = 0; i < 10; i++){
Button button = new Button(activity);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(200, 100);
button.setLayoutParams(lparams);
button.setTag(0);
button.setBackgroundResource(R.drawable.d);
buttonArray[i] = button;
layout.addView(button);
}
Upvotes: 1