Android set height and width of Custom view programmatically

前端 未结 6 1656
感情败类
感情败类 2020-11-28 21:06

I have created a custom view named Graphview . Here is the structure for the GraphView class.

public class GraphView extends View {

    public          


        
相关标签:
6条回答
  • 2020-11-28 21:29
    spin12.setLayoutParams(new LinearLayout.LayoutParams(200, 120));
    

    spin12 is your spinner and 200,120 is width and height for your spinner.

    0 讨论(0)
  • 2020-11-28 21:34

    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);
    
    0 讨论(0)
  • 2020-11-28 21:34

    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.

    0 讨论(0)
  • 2020-11-28 21:36

    You can set height and width like this:

    myGraphView.setLayoutParams(new LayoutParams(width, height));
    
    0 讨论(0)
  • 2020-11-28 21:37

    On Kotlin you can set width and height of any view directly using their virtual properties:

    someView.layoutParams.width = 100
    someView.layoutParams.height = 200
    
    0 讨论(0)
  • 2020-11-28 21:40

    If you know the exact size of the view, just use setLayoutParams():

    graphView.setLayoutParams(new LayoutParams(width, height));
    

    Or in Kotlin:

    graphView.layoutParams = LayoutParams(width, height)
    

    However, if you need a more flexible approach you can override onMeasure() 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 more details about onMeasure() in the android docs.

    0 讨论(0)
提交回复
热议问题