Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 215
Aleks G Avatar asked Mar 28 '26 01:03

Aleks G


2 Answers

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

like image 70
Jong Avatar answered Mar 29 '26 14:03

Jong


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);
like image 40
Thorsten Niehues Avatar answered Mar 29 '26 13:03

Thorsten Niehues



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!