[英]How to create buttons on pressing a button?
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
. 它们是创建的,但是我无法使用
setWidth
, setHeight
或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. 我在
onClick
方法中使用了与上面相同的代码,但是按按钮应用程序崩溃。 Also Button btn=new Button(this)
cannot be used in onClick. 同样,
Button btn=new Button(this)
不能在onClick中使用。 I have done this in i-Pad app easily,but here I am having trouble. 我已经在i-Pad应用程序中轻松完成了此操作,但是在这里遇到了麻烦。
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.
在OnClick中,无法访问“活动”上下文。
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 只需在new Button()中传递上下文并设置布局参数,而不是高度和宽度
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.