簡體   English   中英

android:如何插入沒有layout.xml的底部對齊視圖?

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

我想通過使用addView方法動態插入視圖,就像這樣。

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

如何在插入的視圖下方對齊?

試試這個,你會得到結果:

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

可能是您可以嘗試使用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);

下面的代碼將使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