2013-05-13 44 views
0

我在java中遇到問題。如何在android中總結複選框的值?

package apa.y; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.CheckBox; 
import android.widget.TextView; 



public class myprice extends Activity { 
    /** Called when the activity is first created. */ 


    CheckBox book,pencil; 
    TextView total; 
    int sum=0; 

    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.mymain); 
    pencil = (CheckBox) findViewById(R.id.pencil); 
    book = (CheckBox) findViewById(R.id.book); 
    total = (TextView) findViewById(R.id.total); 

    } 

    public void onClick(View v) { 

     sum = 0; 
     if (pencil.isChecked()) {sum += 10;}else{sum +=0;} 
     if (book.isChecked()) {sum += 5;}else{sum +=0;} 

     total.setText("Total: "+sum); 

    } 
} 

如果書和鉛筆是複選框和1 textview,如何總結它?我現有的代碼不起作用。

回答

1

你在點擊?複選框?那麼你需要某種傾聽者的意見。這裏提供了兩種選擇:Android: checkbox listener

如果你想使用,你有它現在的onClick方法,改變這種:

public class myprice extends Activity implements OnClickListener { 

,並確保您設置OnClickListener兩個複選框:

pencil = (CheckBox) findViewById(R.id.pencil); 
pencil.setOnClickListener(this); 
book = (CheckBox) findViewById(R.id.book); 
book.setOnClickListener(this); 
+0

請等我請我試試。 。 – 2013-05-13 09:14:01

+0

helooooooo IT WORK!謝謝 :)。驚人的hihihi – 2013-05-13 09:25:27

0

創建一個OnCheckedChangeListener並將其設置爲您所有的CheckBox。然後在複選框中選中Integer變量中的+1和Integer變量中的未選中-1。現在你有Integer變量中複選框的最新總和值。

你可以做這樣的事情:

int mCheckSum = 0; 

private OnCheckedChangeListener dmCheckChangeListener = new OnCheckedChangeListener() { 

    @Override 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 

     if (isChecked) { 
      mCheckSum += 1; 
     } else if (isChecked == false) { 
      if (mCheckSum > 0) { 
       mCheckSum -= 1; 
      } 
     } 

    } 
}; 
+0

請等我pleaseeeee。我會嘗試 – 2013-05-13 09:20:55

+0

它工作!謝謝你BRO :) – 2013-05-13 09:24:53

+0

歡迎。如果它工作,那麼你可以標記我的答案是正確的。 – 2013-05-13 09:27:45

相關問題