Android 动态添加时添加的额外切换按钮
我正在尝试动态添加单选按钮 我在项目中拥有的:- 一个活动和三个类扩展切换按钮:- 左切换按钮、右切换按钮和中切换按钮有三个类,它们根据类的名称扩展三个不同的XML,其中包含圆角切换按钮。例如:- LeftToggleButton类的xml和代码:-Android 动态添加时添加的额外切换按钮,android,Android,我正在尝试动态添加单选按钮 我在项目中拥有的:- 一个活动和三个类扩展切换按钮:- 左切换按钮、右切换按钮和中切换按钮有三个类,它们根据类的名称扩展三个不同的XML,其中包含圆角切换按钮。例如:- LeftToggleButton类的xml和代码:- package com.example.radiobuttons; import android.content.Context; import android.widget.LinearLayout; import android.widget
package com.example.radiobuttons;
import android.content.Context;
import android.widget.LinearLayout;
import android.widget.ToggleButton;
public class LeftToggleButton extends ToggleButton{
public LeftToggleButton(Context context, LinearLayout linearLayout) {
super(context);
inflate(context, R.layout.toggle_left_button, linearLayout);
}
}
类似地,其余两个类也是
在主活动中,我正在运行一个循环以添加按钮:-
LinearLayout mainLinear = (LinearLayout) findViewById(R.id.linearMain);
for(int i=0;i<2;i++){
if(i == 0){
LeftToggleButton leftButton = new LeftToggleButton(this, mainLinear);
mainLinear.addView(leftButton);
}
else if(i == 1){
RightToggleButton rightButton = new RightToggleButton(this, mainLinear);
mainLinear.addView(rightButton);
}
else{
MiddleToggleButton middleButton = new MiddleToggleButton(this, mainLinear);
mainLinear.addView(middleButton);
}
}
LinearLayout mainLinear=(LinearLayout)findViewById(R.id.linearMain);
对于(inti=0;我可以删除你的else-if部分..即只使用if-and-else部分..因为这里的middlebutton永远不会通过这个逻辑。只需检查发生了什么..你用什么方法运行这个循环?onCreate
?否则像iya一样就可以了..循环也可以超过2个。我需要所有的三个按钮所以..chan之后的输出是什么格言。。
LinearLayout mainLinear = (LinearLayout) findViewById(R.id.linearMain);
for(int i=0;i<2;i++){
if(i == 0){
LeftToggleButton leftButton = new LeftToggleButton(this, mainLinear);
mainLinear.addView(leftButton);
}
else if(i == 1){
RightToggleButton rightButton = new RightToggleButton(this, mainLinear);
mainLinear.addView(rightButton);
}
else{
MiddleToggleButton middleButton = new MiddleToggleButton(this, mainLinear);
mainLinear.addView(middleButton);
}
}