简体   繁体   中英

How to set EditText layout margin programmatically?

How to set EditText layout margin programmatically in Android? I wanna set the margins for the new editText that comes when you press the floatingactionbutton. It's about input of various activities which I want to be placed down a line with each one being placed underneath the one before it. Remember that this is constraint layout.

I have read a lot of posts on how to do so but nothing seems to work for me.

Here is my code:

public class planlaeg extends AppCompatActivity {
    FloatingActionButton fab;
    Button button4;
    private ConstraintLayout mLayout;
    private EditText mEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_planlaeg);
        button4 = (Button) findViewById(R.id.button4);
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openNewActivity();
            }
        });
        TextView textView = findViewById(R.id.textView);
        textView.setText(nyrejse.getValue());

        mEditText = findViewById(R.id.editText);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        mLayout = (ConstraintLayout) findViewById(R.id.planlaeg_l);

        fab.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                mLayout.addView(createNewEditText(mEditText.getText().toString()));
            }
        });
    }

    public void openNewActivity(){
        Intent intent5 = new Intent(this, MainActivity.class);
        startActivity(intent5);
    }

    private EditText createNewEditText(String text) {
        final EditText et = new EditText(this);
        et.setText(text);
        return et;
    }
}

Check this answer for setting margin in general view. But if the EditText is inside ConstraintLayout you have to have constraint on the EditText for the side which you want to add margin. For example, if you want to add margin to the end of the view, you have to set layout_constraintEnd_toEndOf or layout_constraintEnd_toStartOf in the EditText. Check this answer for adding constraint programatically.

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