我创建了一个ListView,它有一个列表项,每个列表项旁边都有一个复选框。可以检查多个盒子。我需要从MainActivity中变量的值来改变,具体取决于检查哪些框。
列表
@SuppressLint("ShowToast")
public class ListOfMajors extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.majorslist);
ListView mylist = (ListView) findViewById(R.id.majorslist);
String[] list={"Mechanical Engineering","Civil Engineering","Computer Engineering","Electrical Engineering","Environmental Engineering","Manufacturing Engineering"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListOfMajors.this,android.R.layout.simple_list_item_multiple_choice,list);
mylist.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mylist.setAdapter(adapter);
}
MainActivity
public class MainActivity extends Activity {
public static double scoreDouble;
TextView score;
EditText gpa;
EditText sat;
EditText act;
Button calc;
CheckBox checkbox;
public void Checkbox(View view){
boolean checked = ((CheckBox) checkbox).isChecked();
if(checked){
Intent myIntent = new Intent(MainActivity.this, ListOfMajors.class);
MainActivity.this.startActivity(myIntent);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gpa = (EditText) findViewById(R.id.gpa);
sat = (EditText) findViewById(R.id.sat);
act = (EditText) findViewById(R.id.act);
checkbox = (CheckBox) findViewById(R.id.checkBox);
score = (TextView) findViewById(R.id.score);
calc = (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String gpaString = gpa.getText().toString();
if (gpaString.equals("")) {
gpaString = "0";
}
double gpaDouble = Double.parseDouble(gpaString);
String satString = sat.getText().toString();
if (satString.equals("")) {
satString = "0";
}
int satInt = Integer.parseInt(satString);
String actString = act.getText().toString();
if (actString.equals("")) {
actString = "0";
}
int actInt = Integer.parseInt(actString);
if (actInt / 36.0 < satInt / 2400.0) {
scoreDouble = (0.6 * gpaDouble * 25)
+ (0.4 * ((double) satInt / 2400.0) * 100.0);
} else {
scoreDouble = (0.6 * gpaDouble * 25)
+ (0.4 * ((double) actInt / 36.0) * 100.0);
}
Intent myIntent = new Intent(MainActivity.this, CollegeList.class);
MainActivity.this.startActivity(myIntent);
}
}
);
}
}
就我而言,如果&#34;机械工程&#34;检查后,变量scoreDouble应该增加100,如果&#34;土木工程&#34;检查它应该增加1000,等等。我将如何做到这一点?
答案 0 :(得分:1)
您可以使用listView方法getCheckedItemPositions()
来查找列表中的哪些元素已被选中。该方法返回一个带有检查位置的稀疏布尔数组。然后,您可以根据给定数组中的元素修改相应的变量。