draw Android UI programmatically [closed]
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this questionif I want开发者_开发技巧 to draw Android UI programmatically, which is the best layout to use....My app will catch a string from server and based upon this string it will draw UI elements like buttons For example if it catches 1001 it means DRAW ,NOT DRAW,NOT DRAW,DRAw...
You can have an XML layout with everything which could be drawn, and then you set the visibility of some of the components to GONE
, depending on what you receive.
Getting a good layout programmatically can be a real pain for complicated layouts (which seems to be what you're going for).
What I would recommend is create a layout that contains all the elements you're going to make. You can arrange them however you want. Then, at runtime you can set their attributed to either View.GONE or View.INVISIBLE.
Else, the absolute easiest layout to use would be LinearLayout. All you have to do is create and add views to it and they will stack on top each other.
The more difficult, but powerful layouts would be FrameLayout and RelativeLayout. Those allow you to set the widgets wherever you want, but you have to adjust them based off gravity and LayoutParams which can get really complicated programmatically.
Try a SurfaceView. It provides a blank drawing surface.
Barry
You can add views (Buttons, TextViews, Layouts) programmatically by first getting the parent view, and then adding the new child view to it. Here's an example.
//This is inside an Activity class, any function you designate
LinearLayout myLayout = (LinearLayout)findViewById(R.id.mylayout);
Button myButton = new myButton(this);
myButton.setText("Click Me");
myLayout.addView(myButton);
EDIT
If you want to create the LinearLayou too, you can set it like this.
//This is inside an Activity class, any function you designate
LinearLayout myLayout = new LinearLayout(this);
Button myButton = new myButton(this);
myButton.setText("Click Me");
myLayout.addView(myButton);
setContentView(myLayout);
精彩评论