1
4つのトグルボタン(最終的には8,12,16)を使用して、切り替え先の位置に応じてそれぞれに値を与えます。トグルボタンのブール値を整数値に変換してから、テキストビューで一緒に加算する
のでtoggle1
は、1つまたはゼロとtoggle2
の値が2またはゼロ(TB4 4または0、TB8 8または0など)のいずれかの値が得られます
を与える私は、現在の値を追加したいですすべてのボタンをまとめてテキスト表示します。
私はちょうど最初の2から始めましたが、その値をdisplayDecimalAnswer
メソッドに取得する方法がわかりません。とてもシンプルに聞こえるので、私は明らかにここで非常に明白なものを紛失している。
私にオビ・ワン・ケノビスを助けてください、あなたは私の唯一の希望です。
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.可能であれば、ローカル変数を試してみて、メソッドが終了したら破壊するようにしてください。あなたはクラスレベルのブール値を持つので、int変数のグローバル化を少なくします。私は(String.valueOf)を書くにはあまりにも怠惰だった:)それは正常に動作します。 – MRX
あなたはスーパースターです。私は2週間これ(私の最初のアプリ)に取り組んできましたし、ついに8つのボタンが動作しています。それはかなり見えるようにして、いくつかの機能を追加する必要があります。 :D – mmmartinnn