2016年7月20日 星期三
傳遞物件類型...use Serializable on android
Score.java... 實作 Serializable interface
public class Score implements Serializable {
private int programming, dataStructure, algorithm;
// 建構子
public Score(int programming, int dataStructure, int algorithm) {
this.programming = programming;
this.dataStructure = dataStructure;
this.algorithm = algorithm;
}
@Override
public String toString() {
NumberFormat nf = NumberFormat.getInstance();
String text = "programming = " + programming +
"\ndataStructure = " + dataStructure +
"\nalgorithm = " + algorithm +
"\nsum = " + nf.format(getSum()) +
"\naverage = " + nf.format(getAverage());
return text;
}
}
然後在 Mainactivity.java ..當按下按鈕之後...把score 加到bundle 裡面...然後傳遞
public void onSubmitClick(View view) {
boolean isValid =
isValid(etProgramming) & isValid(etDataStructure) & isValid(etAlgorithm);
if (!isValid) {
return;
}
int programming = Integer.parseInt(etProgramming.getText().toString());
int dataStructure = Integer.parseInt(etDataStructure.getText().toString());
int algorithm = Integer.parseInt(etAlgorithm.getText().toString());
Intent intent = new Intent(this, ResultActivity.class);
Bundle bundle = new Bundle();
Score score = new Score(programming, dataStructure, algorithm);
bundle.putSerializable("score", score);
intent.putExtras(bundle);
Log.i(TAG, "change to Resultactivity");
startActivity(intent);
}
在 Resultactivity.java...利用 bundle.getSerializable("score") 來get
private void showResults() {
Log.i(TAG, "showResults");
Bundle bundle = getIntent().getExtras();
Object score = bundle.getSerializable("score");
tvResult.setText(score.toString());
}
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言