如何以编程方式在Android中水平对齐两个字段

时间:2017-01-10 10:51:04

标签: android alignment android-linearlayout

我是以编程方式创建线性布局,我想在同一行上对齐两个字段。但我想像预期的那样显示结果。

 lView = new LinearLayout(Main2Activity.this);
                   // lView.setPadding(0,150,0,0);
                    lView.setBackgroundColor(Color.parseColor("#EDFCFC"));
                    lView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

                    Button logout = new Button(Main2Activity.this);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    params.gravity = Gravity.RIGHT;
                    logout.setLayoutParams(params);
                    logout.setText("Logout");


                    logout.setBackgroundColor(Color.parseColor("#F53F37"));
                    lView.addView(logout);
TextView title = new TextView(Main2Activity.this);
                    title.setText("ASSOCIATES");
                    title.setTextColor(Color.parseColor("#2BD865"));
                    title.setTextSize(25);
                    title.setTypeface(null, Typeface.BOLD);
                    title.setGravity(Gravity.CENTER);
                    lView.setOrientation(LinearLayout.VERTICAL);
                    lView.addView(title);


                    TextView title1 = new TextView(Main2Activity.this);
                    title1.setText("Date :");
                    title1.setTextSize(20);
                    lView.setOrientation(LinearLayout.VERTICAL);
                    lView.addView(title1);


                    et1 = new EditText(Main2Activity.this);
                    et1.setWidth(10);
                    et1.setGravity(Gravity.RIGHT);
                    et1.setHint("Date");
                    //lView.setOrientation(LinearLayout.VERTICAL);
                    lView.addView(et1); 

我的实际输出

enter image description here

预期 enter image description here

3 个答案:

答案 0 :(得分:0)

您需要为父LinearLayout设置重力以对齐孩子。

答案 1 :(得分:0)

将线性布局方向设置为水平,如下所示:

                lView.setOrientation(LinearLayout.HORIZONTAL);

答案 2 :(得分:0)

将LayoutParams添加到textviewedittext,您将获得指定的视图。

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.CENTER;

TextView title1 = new TextView(Main2Activity.this);
title1.setLayoutParams(params);
title1.setText("Date :");
title1.setTextSize(20);
lView.setOrientation(LinearLayout.VERTICAL);
lView.addView(title1);
params.gravity = Gravity.LEFT;

et1 = new EditText(Main2Activity.this);
et1.setLayoutParams(params);
et1.setWidth(10);
et1.setGravity(Gravity.RIGHT);
et1.setHint("Date");
lView.setOrientation(LinearLayout.HORIZONTAL);
lView.addView(et1);