tags:

views:

101

answers:

1

I'm trying to build an android application that features a graphical display drawn within a RelativeLayout. I want to place "+" and "-" buttons next to several of the parameters, which are drawn at various points on the canvas. The positions are free-form don't seem to conform to any of the standard XML layouts.

I know how to create the buttons programmatically, but I don't know how to place them over the canvas where I need them to be. I'm assuming that this would be done in the view thread's doDraw() method, after all the graphics have been drawn, but how?

A: 

I struggled with the same problem, and found out great solution.

RelativeLayout rules like "leftOf" or "rightOf" can be implemented programmatically like this:

RelativeLayout container = new RelativeLayout(getApplicationContext());

Button weight = new Button(getApplicationContext());
final int WEIGHT_ID = 0;
weight.setId(WEIGHT_ID);
weight.setText("0.0");
LayoutParams wrapBoth = 
   new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
container.addView(weight, wrapBoth);

Button increaseWeight = new Button(getApplicationContext());
increaseWeight.setText("+");
// Note the difference: RelativeLayout.LayoutParams  in spite of LayoutParams
RelativeLayout.LayoutParams toBeRightOfWeight = 
     new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
container.addView(parameter,wrapBoth);
// Sweet part
clearAirParams.addRule(RelativeLayout.RIGHT_OF, WEIGHT_ID);
container.addView(increaseWeight, toBeRightOfWeight);

So, in code you can create a 'container' RelativeLayout, then add several Views with unique ID's and, finally, create RelativeLayout.LayoutParams object to achieve sweet-like-sugar methods for alignment, like in XML.

furikuretsu