我正在尝试动态添加单选按钮。
我的项目有什么: -
一个Activity和3个类扩展ToggleButtons: -
左,右和中切换按钮是有三个不同的xmls类,它们包含按照类名称的带圆角的切换按钮。例如: -
用于LeftToggleButton类的xml和代码: -
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);
}
}
<?xml version="1.0" encoding="utf-8"?>
<ToggleButton xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_selector_left"
android:drawableLeft="@drawable/ic_launcher"
android:textColor="@android:color/white"
android:textOff="@string/hello_world"
android:textOn="@string/hello_world" />
同样,其余两个班级。
在主要活动中,我正在运行一个循环来添加按钮: -
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);
}
}
预期结果应为: -
但是我得到了这个结果,在我的自定义按钮后,切换按钮会更多: -
请告诉我这里我做错了什么。为什么会有额外的切换按钮?