问题
I have created a custom view named Graphview . Here is the structure for the GraphView class.
public class GraphView extends View {
public GraphView(Context context, float[] values, String title, String[] horlabels, String[] verlabels, boolean type) {
super(context);
........
}
..................
.................
}
I have added the view in a tablerow using addview(). It is working fine. Now I want to set height and width for the GraphView. How to do that?
回答1:
The easy way is to set the size programatically like that :
graphView.setLayoutParams(new LayoutParams(width, height));
This is fine if you know the exact size of the view. However, if you want a more flexible approach, you can override the onMeasure() method to measure the view more precisely depending on the space available and layout constraints (wrap_content, match_parent, or a fixed size).
You can find an example on how to override onMeasure() by looking at the android docs and the LabelView sample in your SDK directory.
回答2:
You can set height and width like this:
myGraphView.setLayoutParams(new LayoutParams(width, height));
回答3:
you can set the height and width of a view in a relative layout like this
ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = 130;
view.setLayoutParams(params);
回答4:
spin12.setLayoutParams(new LinearLayout.LayoutParams(200, 120));
spin12 is your spinner and 200,120 is width and height for your spinner.
回答5:
This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout.
someView.layoutParams = LinearLayout.LayoutParams(100, 200)
This allows to set the width and height (100 and 200) in a single line.
回答6:
On Kotlin you can set width and height of any view directly using their virtual properties:
someView.layoutParams.width = 100
someView.layoutParams.height = 200
来源:https://stackoverflow.com/questions/5042197/android-set-height-and-width-of-custom-view-programmatically