Reputation: 519
I am using following code to create buttons in a horizontal layout using array of button names:
LinearLayout tabView = (LinearLayout) findViewById(R.id.tabView);
tabView.setOrientation(LinearLayout.HORIZONTAL); //Can also be done in xml by android:orientation="vertical"
for (int i = 0; i < tabButtonNames.length; i++) {
Button btnTag = new Button(this);
btnTag.setText(tabButtonNames[i]);
btnTag.setWidth(50);
btnTag.setHeight(14);
btnTag.setTextSize(8);
btnTag.setId(i);
btnTag.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
---the code TODO
});
tabView.addView(btnTag);
}
They are created but I cannot change the height and the width of the buttons using setWidth
, setHeight
or LayoutParam
. Then on pressing a button, I want to create a list of more buttons in my vertical layout using an array of button names. I used the same code as above in onClick
method, but application crashes on pressing button. Also Button btn=new Button(this)
cannot be used in onClick.
I have done this in i-Pad app easily,but here I am having trouble.
Upvotes: 0
Views: 180
Reputation: 17401
Just pass the context in new Button() and set layout params instead of height and width
for (int i = 0; i < tabButtonNames.length; i++) {
Button btnTag = new Button(<-Context->);//You need to pass context just write <ActivityName>.this
btnTag.setText(tabButtonNames[i]);
LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(<width>,<height>);(50,40)
//btnTag.setWidth(50);
//btnTag.setHeight(14);
btnTag.setTextSize(8);
btnTag.setId(i);
btnTag.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
}
});
tabView.addView(btnTag);
btnTag.setLayoutParams(params)
}
Upvotes: 1
Reputation: 15392
Button btn=new Button(this)
is actually referring your clicklistiner, you have to refer your class, Button btn=new Button(classname.this)
or create a simple function outside clickListener.
Upvotes: 1
Reputation: 7306
Use
Button btn = new Button(getApplicationContext());
OR
Button btn = new Button(ActivityName.this);
instead of
Button btn = new Button(this);
As Button requires context. And in OnClick, context of Activity is not accessible.
Upvotes: 6