2016-07-30 1 views
0

소수점 표시의 이진수 값을 보여주는 앱 (내 첫 번째)을 만들려고합니다. 나는 ToggleButton을 사용했는지 여부를 보여주는 1 또는 0의 이미지와 함께 사용하기로 결정했습니다. "이진과 같다 : 1"나는 ToggleButton을 누를 때 표시 할 때 그렇게하는 TextView까지 '1'링크 관리 아래에 마찬가지로 02+ ToggleButtons를 사용하여 버튼의 총 가치를 얻는 방법?

을 위해 나는 두 번째 버튼은 쉽게하지만 5 후 것입니다 추가 생각했다 (10?) 시간의 인터넷 검색 및 실험 나는 그것을 어떻게하는지 전혀 모른다.

나는 case breaks을 시도했지만 난 단지 이주 (udacity Android Development for Beginners 지금까지) 내가 어디 다음 또는 경우에 난 갈 생각이 없다 프로그래밍 된대로 올바른 트랙했다 ToggleButtons 예를 들어, 나쁜 생각? toggle1을 선택

1) 경우, 다른 valueOfOnes = 1, valueOfOnes = 0

2) 만약 toggle2 (결국 4, 8, 16을 : 내가해야 할 일을 생각

이있다 ...) 다른 valueOfTwos = 2 = 0

3)에 등 valueOfOnesvalueOfTwos

4) 표시하는 값을 추가하는 방법을 확인하게 선택 in Textview

아래의 코드가 너무 지저분 해 보이지 않기를 바랍니다. 그것은 ... 내 뇌가 이전에 비해 정돈의

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
android:padding="16dp" 
tools:context="com.example.android.binary02.MainActivity"> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="0dp" 
     android:layout_weight="3"> 

     <ToggleButton 
      android:id="@+id/toggle2" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_centerVertical="true" 
      android:layout_margin="10dp" 
      android:layout_weight="1" 
      android:background="@drawable/check" 
      android:focusable="false" 
      android:focusableInTouchMode="false" 
      android:textOff="" 
      android:textOn="" /> 

     <ToggleButton 
      android:id="@+id/toggle1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_centerVertical="true" 
      android:layout_margin="10dp" 
      android:layout_weight="1" 
      android:background="@drawable/check" 
      android:focusable="false" 
      android:focusableInTouchMode="false" 
      android:textOff="" 
      android:textOn="" /> 
    </LinearLayout> 


    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1" 
     android:orientation="horizontal"> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Binary equals: " 
      android:textSize="50sp" /> 

     <TextView 
      android:id="@+id/decimal" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="0" 
      android:textSize="50sp" /> 
    </LinearLayout> 
</LinearLayout> 

CHECK XML 

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<!-- When selected, show one --> 
<item android:drawable="@drawable/one" 
    android:state_checked="true" /> 
<!-- When not selected, show two--> 
<item android:drawable="@drawable/zero" 
    android:state_checked="false"/> 

</selector> 

MainActivity.java :

package com.example.android.binary02; 

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; 
    TextView decimalAnswer; 
    int valueOfOnes = 1; 
    int valueOfTwos = 2; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     toggle1 = (ToggleButton) findViewById(R.id.toggle1); 
     toggle1.setOnCheckedChangeListener(this); 

     toggle2 = (ToggleButton) findViewById(R.id.toggle2); 
     toggle2.setOnCheckedChangeListener(this); 
     decimalAnswer = (TextView) findViewById(R.id.decimal); 
    } 

    @Override 
    public void onCheckedChanged (CompoundButton compoundButton, boolean oneSelected) { 
     if(oneSelected) { 
      int valueOfOnes = 1; 
      addValues(valueOfOnes); 
     } 
     else 
     { 
      int valueOfOnes = 0; 
      addValues(valueOfOnes); 

     } 
    } 

    /** If this method is commented out and relevant changes made to addValues then one button works fine 
    * 
    * @param compoundButton 
    * @param oneSelected 
    */ 
    @Override 
    public void onCheckedChangedTwo (CompoundButton compoundButton, boolean twoSelected) { 
     if(twoSelected) { 
      int valueOfTwos = 2; 
      addValues(valueOfTwos); 
     } 
     else 
     { 
      int valueOfTwos = 0; 
      addValues(valueOfTwos); 
     } 
    } 


    /** 
    * Adds values together. 
    * 
    * If I delete the int valueOfTwos here and replace with +1 or +0 then the app works (but only for one button it looks like both buttons perform the same action) 
    * 
    */ 
    public void addValues(int valueOfOnes, int valueOfTwos) { 
     int totalValues; 
     totalValues = valueOfOnes + valueOfTwos; 
     displayDecimalAnswer(totalValues); 
    } 

    /** 
    * Displays decimal answer. 
    */ 
    public void displayDecimalAnswer(int answer) { 
     TextView decimalView = (TextView) findViewById(R.id.decimal); 
     decimalView.setText(String.valueOf(answer)); 
    } 
} 

편집 : 사란의 대답에 추가하여 아래이 좋은 경로를 따라하는 answer 통합을 시도하는 것에서?

+0

최종 대답은 [여기] (찾을 수 있습니다 http://stackoverflow.com/questions/38905750/converting-togglebutton-boolean-to-integer-values-then-add-together-in-a-textvie) – mmmartinnn

답변

0

결국 사란의 대답의 조합 인 MRX의 here과 나에게서의 게으른 고집이 작동하게되었습니다.

@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; 
     } 
    } 
displayDecimalAnswer(); 
} 

    /** 
    * Displays decimal answer. 
    */ 
    public void displayDecimalAnswer() { 
     int valueOfOnes = (toggle1Status) ? 1 : 0;//Since toggle1Status is class level variable it will be accessibible 
     int valueOfTwos = (toggle2Status) ? 2 : 0; 
     int answer = valueOfOnes + valueOfTwos; 

     TextView decimalView = (TextView) findViewById(R.id.decimal); 
     decimalView.setText(""+answer); 
    } 
1

당신이 이상적으로해야 할 일은 두 토글 모두에 setOnCheckedChangeListener을 넣고 onCheckedChanged 메서드를 구현해야한다는 것입니다. 그런 다음 어느 뷰가 전환되었는지 확인하려면 compoundButton을 사용해야합니다.

코드는 다음과 같아야합니다.

@Override 
onCreate(){ 
    toggle1 = (ToggleButton) findViewById(R.id.toggle1); 
    toggle2 = (ToggleButton) findViewById(R.id.toggle2); 
    toggle1.setOnCheckedChangeListener(this); 
    toggle2.setOnCheckedChangeListener(this); 
} 

@Override 
onCheckedChanged (CompoundButton compoundButton, boolean isChecked){ 
    if(compoundButton == toggle1){ 
     if(isChecked){ 
      //Your code if toggle 1 is checked 
     } else { 
      //Your code if toggle 1 is not checked 
     } 
    } else { 
     if(compoundButton == toggle2){ 
      if(isChecked){ 
       //Your code if toggle 2 is checked 
      } else { 
       //Your code if toggle 2 is not checked 
      } 
     } 
    } 
} 

그리고

은 또한 당신의 코드에서 addValue 방법의 선언은 두 variabales 걸립니다. 즉, 라인 public void addValues(int valueOfOnes, int valueOfTwos)에서 valueOfOnesvalueOfTwos 인 두 개의 변수를 취합니다.

그러나이 메서드를 호출 할 때 하나의 변수 addValues(valueOfTwos) 만 전달하면 오류가 발생합니다.

선언문에서 메서드가 int의 두 변수를 받아 들일 것으로 선언 된 경우 메서드 호출에서 int의 두 변수를 전달해야합니다.

문제를 해결하면 문제를 해결할 수 있습니다.

토글 값을 저장하는 방법입니다.

boolean toggle1Status; 
boolean toggle2Status; 

@Override 
onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { 
    if (compoundButton == toggle1) { 

     if (isChecked) { 
      //Toggle one was turned on. 
      toggle1Status = true; 

      if (toggle2Status) { 
       //Your code if both the toggles are on 
      } else { 
       //Your code if toggle 1 is on and 2 is off 
      } 

     } else { 
      //Toggle one was turned off. 
      toggle1Status = false; 

      if (toggle2Status) { 
       //Your code if toggle 1 is off and toggle 2 is on. 
      } else { 
       //Your code if both the toggles are off. 
      } 

     } 
    } else if (compoundButton == toggle2) { 

     if (isChecked) { 
      //Toggle two was turned on. 
      toggle2Status = true; 

      if (toggle1Status) { 
       //Your code if both the toggles are on 
      } else { 
       //Your code if toggle 1 is off and 2 is on 
      } 

     } else { 
      //Toggle two was turned off. 
      toggle2Status = false; 

      if (toggle1Status) { 
       //Your code if toggle 1 is on and toggle 2 is off. 
      } else { 
       //Your code if both the toggles are off. 
      } 

     } 
    } 
} 

는 기본적으로 우리가 여기서하고있는 것은 우리가 다음 다른 전환의 상태를 확인, 변경되었습니다 전환의 첫 번째 상태를 확인합니다. 그리고 그와 더불어 미래의 사용을 위해 부울 변수에 토글의 현재 상태 값을 저장합니다.

+0

정말 고마워. 확실히 한발 더 가까이에! onCheckedChanged 전에 'public void'에 추가 했습니까? 토글 1에 대해 토글 2와 1을 누르면 '2'가 표시되지만 여전히 두 개의 정수를 허용하는 addValues ​​메서드를 가져올 수 없습니다. 'public void addValues ​​(int valueOfOnes, int valueOfTwos) { int totalValues; totalValues ​​= valueOfOnes + valueOfTwos; displayDecimalAnswer (totalValues); }' MainActivity의 addValues ​​(int, int)에 (int에) 적용 할 수 없습니다. – mmmartinnn

+0

다시 한번 감사드립니다. 이제는 onCheckedChange 메소드의 두 부분에서'addValues ​​(valueOfOnes, valueOfTwos); '가 있습니다. 각 버튼은 잘 작동하지만 'Binary equals : 0' textview는 두 값을 함께 추가하지 않습니다. 가장 최근에 누른 버튼 만 처리하고 다른 버튼의 값을 잊어 버리는 것 같습니다. 토글 1을 누르면 01 = 1이 표시되고 토글 2를 누르면 11 = 2가됩니다. 다시 t1을 누르면 10 = 0이됩니다. 중간에'else'를 꺼내려고했지만 그게 어떻게 돌아가는지는 바뀌지 않았습니다. – mmmartinnn

+0

토글 값을 기억하려면 두 변수를 사용하여 각 토글의 부울 값을 저장하십시오. 즉 toggle one이 켜져 있으면'booleanToggle1'을 true로 설정해야하고, 토글 2가 클릭되면 ** booleanToggle1' 변수를 사용하여 toggle1 **의 상태를 결정할 수 있습니다. 그리고 toggle1이 꺼져있을 때'booleanToggle1'의 값을 false로 다시 설정하는 것을 잊지 마십시오. 그리고 당신은 다른 토글을 위해 당신도 할 수 있습니다. –

관련 문제