简体   繁体   English

如何以编程方式设置 EditText 布局边距?

[英]How to set EditText layout margin programmatically?

How to set EditText layout margin programmatically in Android?如何在 Android 中以编程方式设置 EditText 布局边距? I wanna set the margins for the new editText that comes when you press the floatingactionbutton.我想为按下浮动操作按钮时出现的新 editText 设置边距。 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.但是,如果EditTextConstraintLayout内,则必须对要添加边距的一侧的 EditText 进行约束。 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.例如,如果要在视图的末尾添加边距,则必须在 EditText 中设置layout_constraintEnd_toEndOflayout_constraintEnd_toStartOf Check this answer for adding constraint programatically.检查答案以编程方式添加约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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