將自訂繪圖 View(覆寫 onDraw 繪製 Bitmap/Canvas)與動態建立的 Button 加入同一 RelativeLayout,利用 LayoutParams 定位按鈕於底部左右。
public class SignatureActivity extends Activity implements View.OnClickListener {
private SignatureView signatureView;
private Button saveBtn, clearBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
signatureView = new SignatureView(this);
RelativeLayout root = new RelativeLayout(this);
root.setLayoutParams(new RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
// 簽名視圖
root.addView(signatureView, new RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
// 儲存按鈕 - 左下
saveBtn = new Button(this);
saveBtn.setText("儲存");
saveBtn.setOnClickListener(this);
RelativeLayout.LayoutParams saveParams = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
saveParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
saveParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
saveParams.setMargins(20, 0, 0, 20);
root.addView(saveBtn, saveParams);
// 清除按鈕 - 右下
clearBtn = new Button(this);
clearBtn.setText("清除");
clearBtn.setOnClickListener(this);
RelativeLayout.LayoutParams clearParams = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
clearParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
clearParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
clearParams.setMargins(0, 0, 20, 20);
root.addView(clearBtn, clearParams);
setContentView(root);
}
@Override
public void onClick(View v) {
if (v == saveBtn) { signatureView.save(); }
else if (v == clearBtn) { signatureView.clear(); }
}
}
View,onDraw 中繪製 Bitmap 與路徑。invalidate() 觸發重繪。save() 將 Bitmap 壓縮存檔,clear() 重置路徑並 invalidate()。