android - 如何在android中对齐图像

标签 android android-layout android-linearlayout

我正在我的 Activity 中动态添加控件。同时我添加了一个编辑框和按钮,但在图像对齐方面遇到了一些问题。

enter image description here

这是我的代码,它为 editText 和 Button 添加广告,并返回到垂直对齐的线性布局。

 LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(0);

        final EditText textView = new EditText(this);
        textView.setLayoutParams(lparams);
        textView.setSingleLine(true);

        final LayoutParams lparams1 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        final Button button = new Button(this);
        textView.setLayoutParams(lparams1);


        if(id == R.id.new_alternate_number_button)
        {
            if(contactNumber == "")
            {
            textView.setHint("Enter contact Number");
            }
            else
            {
             textView.setText(contactNumber);
            }
            textView.setInputType(InputType.TYPE_CLASS_PHONE); //to popup numpad
        }
        else
        {
            if(contactEmailID == "")
            {
                textView.setHint("Enter Email ID      ");       
            }
            else
            {
                textView.setText(contactEmailID);
            }

        }
        button.setBackgroundResource(R.drawable.ic_delete);

        button.setBackgroundResource(R.drawable.ic_delete);    
        button.setOnClickListener(deleteView);

        layout.addView(textView);
        layout.addView(button);

textView.post(new Runnable() {
            public void run() {
                textView.requestFocus();
                  InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                  imm.showSoftInput(textView, InputMethodManager.SHOW_IMPLICIT);

            }
        });

        return layout;   

在我的 XML 文件中,我声明了垂直对齐的线性布局,即图标应该在屏幕的末尾,EditText 应该左对齐。我还需要在 EditText 和图像之间留一个空格。

提前致谢

最佳答案

您的 LayoutParams 宽度设置为 WRAP_CONTENT 而不是 FILL_PARENT(或 MATCH_PARENT)。

我在类似情况下使用的“模式”是,即使我动态添加新行/部分,我仍然将它们布局在该行的 xml 文件中,然后我动态膨胀并找到元素通过 id,并绑定(bind)到他们。有点像我们处理列表项的方式,除了在这种情况下,您没有使用列表。

通过将布局保留在 XML 文件中,可以更轻松地制作您想看到的原型(prototype)、添加填充等。如果您无法让 LinearLayout 工作,您甚至可以使用 RelativeLayout。同样,您可以在代码中完成所有这些,但在 XML 中进行布局提供了更大的灵 active (并且在我看来更容易处理)

关于android - 如何在android中对齐图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13074523/

相关文章:

java - Android 操作未显示在操作栏中

java - 如何使用 GSON 有效地延迟加载 JSON 文件的特定元素?

java - 如何从MySQL数据库获取数据到android

android - 3 个 textView 项目根据其长度换行

Android:制作没有布局土地的横向 View ?

android - 在 LinearLayout 中重叠 TextView

android - 将初始数据提供给 fragment 的正确方法?

Android 动画方法和可见性 GONE

java - 布局无法正常工作

android - 如何消除android layout.xml中的warning : "missing contentDescription"