Android - add subview with layout params at specific index (in code)

六眼飞鱼酱① 提交于 2019-12-11 01:36:38

问题


I may be missing something, but I can't find a way to add a subview to a view at a specified index with specific layout params. There's addView(View v, LayoutParams lp) and there's addView(View v, int index) - but I can't find a way to specify both.

What am I missing?


回答1:


Why, there's a method with both: addView(View child, int index, ViewGroup.LayoutParams params): Here.




回答2:


Here is an example. I use it to show a progress indicator on any view.

final ViewGroup rootFrameLayout = (ViewGroup) activity.getWindow().peekDecorView();
LayoutInflater li = LayoutInflater.from(activity);
progressView = li.inflate(R.layout.progressindicator, null);
rootFrameLayout.addView(progressView);

Here is a sample layout file (id is R.layout.progressindicator)

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

<ProgressBar
    android:id="@+id/progressBar1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="3dp"
    android:layout_toRightOf="@+id/progressBar1"
    android:maxLines="3"
    android:lines="3"
    android:background="#88000000"
    android:textColor="#ffffff"
    android:text="@string/waitingForServer" />

Just in case you want to change the layout also dynamically then you can call the methods of the elements in the layout. Like this:

TextView textView = (TextView) progressView.findViewById(R.id.textView1);
textView.setMaxLines(lines);
textView.setLines(lines);
textView.setVisibility(View.VISIBLE);


来源:https://stackoverflow.com/questions/8929439/android-add-subview-with-layout-params-at-specific-index-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!