简体   繁体   中英

How can I set a view's gravity and layout_gravity programmatically in Java instead of XML?

For my activity, we were tasked with creating the views entirely programmatically (not allowed to use XML).

I created what I want the layout to look like in XML. 我希望布局在 XML 中的样子

but I'm having trouble getting my contentEditText and the gravities to correctly set the, up as I've done in the XML file.

This is what I have for my view.

public class NoteGridLayout extends GridLayout {

  public NoteGridLayout(final Context context, EditText titleEditText, Spinner spinner, EditText contentEditText, Button backButton) {
    super(context);

    setColumnCount(2);

    GridLayout.Spec colSpec, rowSpec;
    colSpec = GridLayout.spec(0, 1, 1);
    rowSpec = GridLayout.spec(0, 0, 0);
    GridLayout.LayoutParams titleParams = new GridLayout.LayoutParams(rowSpec, colSpec);

    colSpec = GridLayout.spec(1,1,1);
    rowSpec = GridLayout.spec(0,0,0);
    GridLayout.LayoutParams spinnerParams = new GridLayout.LayoutParams(rowSpec, colSpec);

    colSpec = GridLayout.spec(0,2,1);
    rowSpec = GridLayout.spec(1,1,1);
    GridLayout.LayoutParams contentParams = new GridLayout.LayoutParams(rowSpec, colSpec);

    colSpec = GridLayout.spec(0,2,1);
    rowSpec = GridLayout.spec(2,1,0);
    GridLayout.LayoutParams buttonParams = new GridLayout.LayoutParams(rowSpec, colSpec);

    titleParams.width = 0;
    titleParams.height = LayoutParams.WRAP_CONTENT;
    spinnerParams.width = 0;
    spinnerParams.height = LayoutParams.WRAP_CONTENT;
    contentParams.width = 0;
    contentParams.height = 0;
    buttonParams.width = LayoutParams.MATCH_PARENT;
    buttonParams.height = LayoutParams.WRAP_CONTENT;
    contentParams.setGravity(Gravity.TOP);

    titleEditText.setLayoutParams(titleParams);
    spinner.setLayoutParams(spinnerParams);
    contentEditText.setLayoutParams(contentParams);
    backButton.setLayoutParams(buttonParams);


    addView(titleEditText);
    addView(spinner);
    addView(contentEditText);
    addView(backButton);
  }
}

The two main problems I'm having are: 1. The titleEditText is not appearing to span an entire column, rather, the spinner is taking up the whole two columns. 2. The contentEditText gravity is not able to be set, placing the text at the top of the box.

What do I need to do to fix these two problems?

For layout_gravity following is a code snippet,

LinearLayout.LayoutParams params = new 
LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.CENTER;
yourView.setLayoutParams(params);

For Gravity use following line,

yourLayout.setGravity(Gravity.CENTER)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM