简体   繁体   English

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

[英]android: How to insert a bottom aligned view without layout.xml?

I want to insert views dynamically by using addView method, like this. 我想通过使用addView方法动态插入视图,就像这样。

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

How can I align bottom the inserted view? 如何在插入的视图下方对齐?

Try this you will get the result: 试试这个,你会得到结果:

    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);

May be you could try to use a RelativeLayout instead of a ViewGroup , like this: 可能是您可以尝试使用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);

Below code will align textview with bottom 下面的代码将使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);

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

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