0

I have a few issues with setting LayoutParams and other parameters of my layouts/views programmatically. I cannot specify these in a XML layout file because whether they appear depends on the data held in the database.

The following is a function I use to create a new "Section" which consists of a FrameLayout with its children being View and TextView:

public FrameLayout createSection(long id, String name) {
    FrameLayout frame = new FrameLayout(this);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 100);
    params.setMargins(15, 15, 15, 15);
    frame.setLayoutParams(params);

    View view = new View(this);
    LayoutParams viewParams = new LayoutParams(LayoutParams.MATCH_PARENT, 100);
    view.setLayoutParams(viewParams);
    view.setId(toIntExact(id));
    view.setBackgroundResource(R.color.colorButton);
    frame.addView(view);

    TextView text = new TextView(this);
    LayoutParams textParams = new LayoutParams(LayoutParams.MATCH_PARENT, 100);
    textParams.setMarginStart(15);
    text.setGravity(Gravity.CENTER);
    text.setTextAlignment(TextView.TEXT_ALIGNMENT_TEXT_START);
    text.setTextColor(getResources().getColor(R.color.colorTextSecondary));
    text.setText(name);
    frame.addView(text);

    return frame;
}

The parent of this newly created FrameLayout is LinearLayout and so based on the other similar questions on StackOverflow I figured setting parameters for FrameLayout should be done through LinearLayout.LayoutParams. However, this does not make a change. The initial XML page contains this: Initial XML page

The first "SECTION" is created in the XML file, and the other two are created through 'createSection' function. This is the outcome: Design outcome

The issue is that the margins are not set properly and the TextView doesn't seem to care about the Gravity + TextAlignment combination that I'm using.

I would appreciate any help that I could get to resolve this issue.

curiousdev
  • 626
  • 8
  • 24

1 Answers1

0

I apologise for wasting anyone's time. The code seems to work and the margin sizes are different due to these being set in terms of pixels (px) rather than dp as it is in the XML file.

I also forgot to add text.setLayoutParams(textParams); to the TextView object.

curiousdev
  • 626
  • 8
  • 24