简体   繁体   中英

How to change the width of an EditText object programmatically?

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.

You can use

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

or

editTextSpieler1.getLayoutParams().width=200;

Try the following:

int width = 100;
int height = 50;
LayoutParams params = new LayoutParams(width, height);
EditText mEditText = new EditText(this);
mEditText.setLayoutParams(params);

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