在MainActivity
和ChangeBrush
之間傳遞畫筆大小和畫筆形狀。Android - 通過兩個活動之間的putExtras傳遞幾個參數
主營:
static final int ACTIVITY_BRUSH_SIZE_REQUEST_CODE = 2;
static final int ACTIVITY_BRUSH_SHAPE_REQUEST_CODE = 3;
public void onClickBrush(View view) {
Intent intent = new Intent(MainActivity.this, ChangeBrush.class);
startActivityForResult(intent, ACTIVITY_BRUSH_SIZE_REQUEST_CODE);
startActivityForResult(intent, ACTIVITY_BRUSH_SHAPE_REQUEST_CODE);
}
ChangeBrush:
public void onClickChangeBrushSize(View view) {
String size = view.getTag().toString().;
// return the brush size to main activity
Bundle bundle = new Bundle();
bundle.putString("size", size);
Intent intent = new Intent();
intent.putExtras(bundle);
setResult(Activity.RESULT_OK, intent);
finish();
}
public void onClickChangeBrushShape(View view) {
String shape = view.getTag().toString();
// return the brush shape to main activity
Bundle bundle = new Bundle();
bundle.putString("shape", shape);
Intent intent = new Intent();
intent.putExtras(bundle);
setResult(Activity.RESULT_OK, intent);
finish();
}
SelectBrush
活動佈局:
當用戶點擊size
按鈕,在按鈕活動,他們可以通過size
和shape
到MainActivity
。在MainActivity
中,我使用onActivityResult
來設置畫筆大小和形狀。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
String color = bundle.getString("color");
String size = bundle.getString("size");
String shape = bundle.getString("shape");
switch(requestCode) {
case ACTIVITY_COLOR_REQUEST_CODE:
fingerPainterView.setColour(Color.parseColor(color)); // set new color value
case ACTIVITY_BRUSH_SIZE_REQUEST_CODE:
Log.d("FingerPainter", "Main activity change brush size to " + size);
case ACTIVITY_BRUSH_SHAPE_REQUEST_CODE:
Log.d("FingerPainter", "Main activity change brush shape to " + shape);
}
} else if(resultCode == RESULT_CANCELED) {
Log.d("FingerPainter", "MainActivity canceled");
}
}
這將記錄的返回值:
D/FingerPainter: Main activity change brush shape to null
D/FingerPainter: Main activity change brush size to null
D/FingerPainter: Main activity change brush shape to SQUARE
看來返回值可以對應於正確的意圖。我不知道爲什麼它記錄了兩次形狀信息。 finish()
有什麼不對嗎?我希望用戶選擇大小和形狀,然後返回到主要活動。
如果方法錯了,應該怎麼做才能通過這兩個值?
你已將哪些按鈕映射到'onClickBrush'?他們全部?您應該將尺寸和形狀按鈕分成兩個單獨的意圖。 –
@ cricket_007'onClickBrush'啓動'ChangeBrush'活動。在'ChangeBrush'活動中,我將大小和形狀分爲兩個意圖(方法)。 – Helen
看起來'onClickBrush'此刻兩次啓動'ChangeBrush'。 –