我有两个切换按钮,每次按下时都会发出不同的字符串代码。但问题是按钮发送相同的字符串代码'101',我无法弄清楚如何让他们发送不同的代码'101'& '102'。有什么建议吗?
java代码
public void onToggleClicked(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
String str = "101".toString();
sendToServer(str);
} else {
String str = "000".toString();
sendToServer(str);
}
}
public void onToggleClicked1(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
String str = "201".toString();
sendToServer(str);
} else {
String str = "000".toString();
sendToServer(str);
}
xml代码
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:layout_x="30dp"
android:layout_y="135dp"
android:onClick="onToggleClicked"
android:textOff="Light1- OFF"
android:textOn="Light1- ON"
android:textSize="40dip" />
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:layout_x="30dp"
android:layout_y="440dp"
android:onClick="onToggleClicked"
android:text="ToggleButton"
android:textOff="Light2- OFF"
android:textOn="Light2- ON"
android:checked="false"
android:textSize="40dip" />
答案 0 :(得分:0)
您的切换按钮正在调用相同的功能。将xml中的一个更改为:
android:onClick="onToggleClicked1"
答案 1 :(得分:0)
android:onClick="onToggleClicked"
每次调用相同的时,在布局中
所以再做一次
android:onClick="onToggleClicked1"
更好的方法和理解为第一个按钮
编写这样的代码 ToggleButton b = (ToggleButton) findViewById(R.id.togglebutton);
// attach an OnClickListener
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// your click actions go here
}
});
为第二个按钮编写这样的代码
ToggleButton b1 = (ToggleButton) findViewById(R.id.toggleButton1);
// attach an OnClickListener
b1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// your click actions go here
});
答案 2 :(得分:0)
试试这个..
ToggleButton button1 = (ToggleButton) findViewById(R.id.toggleButton);
ToggleButton button2 = (ToggleButton) findViewById(R.id.toggleButton1);
button1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
String str = "101";
sendToServer(str);
} else {
String str = "000";
sendToServer(str);
}
}
});
button2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
String str = "201";
sendToServer(str);
} else {
String str = "000";
sendToServer(str);
}
}
});
或者
public void onToggleClicked(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if(R.id.togglebutton == view.getId()){
if (on) {
String str = "101".toString();
sendToServer(str);
} else {
String str = "000".toString();
sendToServer(str);
}
}
if(R.id.togglebutton1 == view.getId()){
if (on) {
String str = "201".toString();
sendToServer(str);
} else {
String str = "000".toString();
sendToServer(str);
}
}
}