Add a button to an onDraw call in Android
I'm using the code below for drawing simple 2D graphics (which I found on DroidNova - very useful!), and I would like to add a button which I have defined in an XML file (string name and location). I can't see how to add the button to the screen (while still showing the graphics from the onDraw call...
Update
I've updated the code below based on the answer. I can get the rectangle to draw, but it does not show the button.
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Drawresult();
}
protected void Drawresult() {
// Create a new linear layout to display out custom graphics and a button.
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
// Add our custom pa开发者_运维问答nel.
mainLayout.addView(new Panel(this));
// Create and setup our button.
Button myButton = new Button(this);
myButton.setText("Tap Me");
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
// Add our button to the layout.
mainLayout.addView(myButton);
// Set this activity's content to our layout.
setContentView(mainLayout);
}
class Panel extends View {
public Panel(Context context) {
super(context);
}
@Override
public void onDraw(Canvas canvas) {
Rect r = new Rect();
r.set(60, 60, 260, 77);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
canvas.drawRect(r, paint);
}
}
}
Change your constructor to this (Assuming you have subclassed Activity. Otherwise post more of your code):
protected void Drawresult() {
// Create a new linear layout to display out custom graphics and a button
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
// Add our custom panel
mainLayout.addView(new Panel(this));
// Create and setup our button
Button myButton = new Button(this);
myButton.setText("Tap Me");
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Put your click logic here
}
});
// Add our button to the layout
mainLayout.addView(myButton);
// Set this activity's content to our layout
setContentView(mainLayout);
}
Assuming DrawResult is extending activity, you need to add a LinearLayout to it instead of the Panel View, and add the Button and the Panel to that layout.
精彩评论