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.
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.
Button btn=new Button(this)
实际上是指您的clicklistiner,您必须引用您的class, Button btn=new Button(classname.this)
或在clickListener之外创建一个简单函数。
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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.