android:如何插入没有layout.xml的底部对齐视图?

时间:2012-07-10 08:38:46

标签: android

我想使用addView方法动态插入视图,就像这样。

TextView view = new TextView(this);
view.setText("foo");
ViewGroup parentView = (ViewGroup) findViewById(R.id.main_layout);
parentView.addView(view);

如何在插入的视图底部对齐?

3 个答案:

答案 0 :(得分:4)

试试这个你会得到结果:

    RelativeLayout parent = (RelativeLayout) findViewById(R.id.llayout);
        TextView textView = new TextView(this);
        textView.setText("foo");
    RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, textView.getId());
    textView.setLayoutParams(params);

    parent.addView(textView);

答案 1 :(得分:1)

可能您可以尝试使用RelativeLayout代替ViewGroup,如下所示:

    RelativeLayout parent = (RelativeLayout) findViewById(R.id.layout_parent);
    TextView tv = new TextView(this);
    tv.setText("foo");

    RelativeLayout.LayoutParams lp= new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, tv.getId());
    tv.setLayoutParams(lp);

    parent.addView(tv);

答案 2 :(得分:1)

下面的代码会将textview与底部对齐

   TextView view = new TextView(this);
   view.setText("foo");

   RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
           ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
   params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, view.getId());

   view.setLayoutParams(params);
   ViewGroup parentView = (ViewGroup) findViewById(R.id.viewgroup);
   parentView.addView(view);