0

I'd like to change the width of an EditText object programmatically without creating the view with xml before.

public class TableFragment extends Fragment{

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
    View view = inflater.inflate(R.layout.fragment_table, container, false);

    DisplayMetrics displayMetrics = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int dHeight = displayMetrics.heightPixels;
    int dWidth = displayMetrics.widthPixels;

    TableLayout tableLayout = view.findViewById(R.id.tableLayout);
    EditText editTextSpieler1 = new EditText(getActivity());
    LayoutParams layoutparams = new LayoutParams(
            dWidth/4,
            WRAP_CONTENT);
    editTextSpieler1.setHint("Name");
    editTextSpieler1.setLayoutParams(layoutparams);
    tableLayout.addView(editTextSpieler1);

    return view;
}}

When creating the EditText view with xml and creating the object with findViewById setting the width works just fine. Yet when I start up the app with the code shown above, the EditText object's width is 100% of the display width.(instead of 25%)

Thanks in advance.

Solution:

tableLayout.addView(editTextSpieler1);
editTextSpieler1.getLayoutParams().width=((int)dWidth/4);

Chnaging the width of the view after it's being addded worked.

  • possible duplicate of https://stackoverflow.com/questions/9224927/how-to-set-edittext-box-height-and-width-programmatically-in-android?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Ashwin K Kumar May 09 '18 at 10:25
  • No, that's what I've tried and done as shown above –  May 09 '18 at 10:26

2 Answers2

0

You can use

editTextSpieler1.getLayoutParams().width=((int)dWidth/4);

or

editTextSpieler1.getLayoutParams().width=200;
Rahul Chaudhary
  • 1,059
  • 1
  • 6
  • 15
0

Try the following:

int width = 100;
int height = 50;
LayoutParams params = new LayoutParams(width, height);
EditText mEditText = new EditText(this);
mEditText.setLayoutParams(params);
Thorvald
  • 3,424
  • 6
  • 40
  • 66
  • The height changed, but not the width, still at 100% display width. I also can't use "this" since this is a fragment. –  May 09 '18 at 10:48
  • double check if the width is hard coded somewhere in the XML – Thorvald May 09 '18 at 15:36