【问题标题】:Set position of an EditText and TextView in a RelativeLayout programatically以编程方式在 RelativeLayout 中设置 EditText 和 TextView 的位置
【发布时间】:2015-07-11 14:16:58
【问题描述】:

我在 main.xml 中定义了一个 RelativeLayout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
</RelativeLayout>

并在 onCreate 中以编程方式添加 TextView 和 EditText:

public void onCreate(Bundle savedInstanceState){
setContentView(R.layout.main);

addContentView(customGlView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

addContentView(myTextView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addContentView(myEditText, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}

它们都出现了,但在左上角重叠。我花了几个小时来弄清楚如何将它们放置在彼此下方,或者一个在屏幕的左角,另一个在右角。如果我通过 main.xml 添加它们,它们都不会出现。谁能给我一个正确方向的提示?

【问题讨论】:

    标签: android android-layout android-relativelayout


    【解决方案1】:

    对于RelativeLayout,您需要指定元素的相对位置,使用LayoutParams

    myTextView.setId(1);
    myEditText.setId(2);
    
    addContentView(myTextView, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    
    final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
    params.addRule(RelativeLayout.BELOW, myTextView.getId());
    addContentView(myEditText, params);
    

    【讨论】:

    • 不幸的是,这不起作用。我已经通过 setId() 为两个视图分配了 ID,就像 Raoul Georges 的回答一样,但它们仍然相互重叠。
    • 嗯,很奇怪。您确定您使用的是不同的 LayoutParams 变量吗?如果你重复使用相同的,你会得到不可预测的结果
    • 是的,我为每一个使用一个不同的 LayoutParams。一个是 BELOW,另一个是 ABOVE。
    • 您不需要同时指定两者:开始放置您的第一个视图,然后指出第二个视图与第一个视图的相对位置 - 我编辑了答案以准确显示您需要做什么,它应该可以工作(未经测试,我在工作)
    • @Guillaume:嗨,我已经尝试过您的代码,但它在 param.addRule(...) 处出现错误。似乎该方法不适用于 LayoutParams,仅适用于 RelativeLayout.LayoutParams .你确定这行代码吗?
    【解决方案2】:

    向您的 LayoutParams 添加一个规则,它将一个文本视图设置在另一个文本视图下方..

    RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    
    TextView tv1 = new TextView(this); 
    tv1.setId(1); 
    tv1.setText("myTextView"); 
    
    params1.addRule(RelativeLayout.BELOW, tv1.getId()); 
    TextView tv2 = new TextView(this); 
    

    【讨论】:

      【解决方案3】:

      我无法使用 RelativeLayout 解决这个问题,但使用 LinearLayout 完全可以满足您的需求。

      addView(myEditText);
      

      或者您可以使用this method 将它们添加到您想要的任何位置。比如可以先添加myEditText,然后在myEditText上面添加myTextView:

      addView(myEditText);
      addView(myTextView, 0);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-28
        • 2011-03-09
        • 2016-12-16
        • 1970-01-01
        • 2011-11-10
        • 2013-11-29
        • 2011-12-16
        相关资源
        最近更新 更多