1
我想使用四个togglebuttons(最终为8,12或16),并根据切换到的位置给每个值赋予值。将togglebutton布尔值转换为整数值,然后在文本视图中加在一起
所以toggle1
会给的值1或0和toggle2
会给两个或零(TB4 4或0,TB8 8或0等)
我然后要添加的电流值的值所有按钮组合在一起并以文本视图显示。
我刚刚开始使用前2个,但不知道如何将这些值存入displayDecimalAnswer
方法。我明显错过了一些非常明显的东西,因为听起来很简单。
帮助我Obi Wan Kenobis你是我唯一的希望。
package com.example.android.binary04;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener {
ToggleButton toggle1;
ToggleButton toggle2;
ToggleButton toggle4;
ToggleButton toggle8;
TextView decimalAnswer;
int totalValues;
boolean toggle1Status;
boolean toggle2Status;
boolean toggle4Status;
boolean toggle8Status;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggle1 = (ToggleButton) findViewById(R.id.toggle1);
toggle2 = (ToggleButton) findViewById(R.id.toggle2);
toggle4 = (ToggleButton) findViewById(R.id.toggle4);
toggle8 = (ToggleButton) findViewById(R.id.toggle8);
toggle1.setOnCheckedChangeListener(this);
toggle2.setOnCheckedChangeListener(this);
toggle4.setOnCheckedChangeListener(this);
toggle8.setOnCheckedChangeListener(this);
decimalAnswer = (TextView) findViewById(R.id.decimal);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (compoundButton == toggle1) {
if (isChecked) {
toggle1Status = true;
} else {
toggle1Status = false;
}
} else if (compoundButton == toggle2) {
if (isChecked) {
toggle2Status = true;
} else {
toggle2Status = false;
}
}
}
/**
* Here I wanted to give a int value to boolean whether each togglebutton
* is clicked or not. Then add the value of each button together
*/
int valueOfOnes = (toggle1Status) ? 1 : 0;
int valueOfTwos = (toggle2Status) ? 2 : 0;
int answer = valueOfOnes + valueOfTwos;
/**
* Displays decimal answer.
*/
public void displayDecimalAnswer(int answer) {
TextView decimalView = (TextView) findViewById(R.id.decimal);
decimalView.setText(String.valueOf(answer));
}
}
最好的,感谢工作正常。将添加一个月的其他按钮。但要澄清: 1:您将displayDecimalAnswer添加到onCheckedChanged方法。 2:在displayDecimalAnswer方法内移动int,因为它们是类级别的。 和3:更改了setText以包含空引号。这是做什么的? – mmmartinnn
1.由于您实现了切换列表的切换列表,因此它将是更新值的最佳位置。 2.首先,你应该尝试使用局部变量,如果可能的话,一旦方法完成其工作,将会破坏局部变量。你有类级布尔值,所以它使用较少的全局变量。 3.我懒得写(String.valueOf):)它会正常工作。 – MRX
你是一位超级明星。我一直在做这个(我的第一个应用程序)两个星期,终于有8个按钮的工作。需要让它看起来很漂亮,现在再添加一些功能。 :d – mmmartinnn