How to Add a View Programmatically to Relativelayout

How to add a view programmatically to RelativeLayout?

Heres an example to get you started, fill in the rest as applicable:

TextView tv = new TextView(mContext);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.leftMargin = 107
...
mRelativeLayout.addView(tv, params);

The docs for RelativeLayout.LayoutParams and the constructors are here

Add view programmatically to RelativeLayout android

You are aligning the textviews with button tops and lefts here:

    textparams.addRule(RelativeLayout.ALIGN_TOP, btn.getId());
textparams.addRule(RelativeLayout.LEFT_OF, btn.getId());

You need to do the same for the ImageButtons - except align the first one with the parent, then each subsequent one you need to align the top to the previous ImageButton (here is fake code):

    btn.addRule(RelativeLayout.ALIGN_BOTTOM, btnAbove.getId());

Then keep a reference to the previous button in "btnAbove" at the end of your loop like:

btnAbove = btn;

Programmatically add view one below other in relative layout

Important: Remember to set the ID for each view.

RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(layoutParams);

RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

TextView tv1 = new TextView(this);
tv1.setId(1);
tv1.setText("textView1");

TextView tv2 = new TextView(this);
params2.addRule(RelativeLayout.RIGHT_OF, tv1.getId());
tv2.setId(2);
tv2.setText("textView2");

TextView tv3 = new TextView(this);
params3.addRule(RelativeLayout.BELOW, tv1.getId());
tv3.setId(3);
tv3.setText("textView3");

TextView tv4 = new TextView(this);
params4.addRule(RelativeLayout.RIGHT_OF, tv3.getId());
params4.addRule(RelativeLayout.ALIGN_BOTTOM, tv3.getId());
tv4.setId(4);
tv4.setText("textView4");

layout.addView(tv1, params1);
layout.addView(tv2, params2);
layout.addView(tv3, params3);
layout.addView(tv4, params4);

Relative Layout adding views programmatically one below other not aligning correctly

I was using the index of the for loop as id for the textViews which I changed to make Android generate Id for it as below and it is working fine now as expected.

I changed the line

textView.setId(i)

to

textView.setId(ViewGroup.generateViewId())

Thanks.

Android: Add textViews in RelativeLayout Programmatically

params1.addRule(RelativeLayout.BELOW, tv.getId());

You are setting it to be below itself?

If you want them below eachother do it this way:

RelativeLayout journals = (RelativeLayout);
findViewById(R.id.JournalSearchListView);
LinearLayout lL = new LinearLayout(context);
lL.setOrientation(LinearLayout.VERTICAL);

for (int i=0;i< authorNames.size();i++) {
TextView tv = new TextView(this);
tv.setId(i);
tv.setText(authorNames.get(i));
tv.setTextColor(Color.BLACK);
Integer a = tv.hashCode();
map.put(a,authorNames.get(i));

if(i!=0){
params1.addRule(RelativeLayout.BELOW, i-1);
}

tv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
System.out.println("Clicked "+ map.get(v.hashCode()) );
}
});

lL.addView(tv);

}

journals.addview(lL);

How to add View outside RelativeLayout to RelativeLayout programmatically

RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams( RelativeLayout.WRAP_CONTENT,RelativeLayout.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW,R.id.rv_comment);
params.setMargin(0,16,0,0);
tv.setLayoutParams(params);

Programmatically setting TextView to RelativeLayout.CENTER_OF_PARENT

The setContentView() call is supposed to be used to set the layout of the full screen. What you're doing currently in your Activity code is setting just a TextView as the full view of the screen, so the Activity has no reference to the XML layout that you created. This is why your 3 lines of code at the end fail, because the TextView is trying to setup its LayoutParams for how its parent should place and measure it, however it has no parent in this context. What I would recommend doing is giving an id attribute to the RelativeLayout in the XML to get a reference to it in Activity code like so:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="home_screen_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"/>

Then in your Activity code, adjust it so that you call with the resource id of your XML file. If we assume it's called act_main.xml in the layout folder of your resources directory (i.e. in src/main/resources/layout/act_main.xml), you would call setContentView(R.layout.act_main) as the first line in onCreate() after the super() call so that the framework has an opportunity to parse your XML and inflate it (i.e. instantiate, make calculations on the size and
determine placement of its components among other things). After that, use findViewById(R.id.home_screen_layout) to get a reference to that RelativeLayout so that you may create a new TextView and add it to your already inflated layout.

package com.example.android.testerapp1;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

// make your view components private members as findViewById calls are expensive for the framework
private RelativeLayout homeScreenLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Have the activity inflate the XML file with your RelativeLayout
setContentView(R.layout.act_main);

// Now that it is inflated, get a reference to that parent
homeScreenLayout = (RelativeLayout) findViewById(R.id.home_screen_layout);

// Dynamically create a TextView associated with this Activity's context
TextView homeScreen = new TextView(this);
homeScreen.setText("Welcome to Test App 001" + "\nThis TextView was created dynamically in Java!");
homeScreen.setTextSize(24);
homeScreen.setTextColor(Color.CYAN);
homeScreen.setCursorVisible(true);
homeScreen.setPadding(16,56,16,56);
homeScreen.setBackgroundColor(Color.BLACK);
homeScreen.setGravity(Gravity.CENTER);

//dynamically set width to dp (converted to pixels ~600) and height to 'wrap content'
// convert dp amount to pixels for size
final float scale = getResources().getDisplayMetrics().density;
int pixelWidth = (int) (2000 / scale + 0.5f);

// Adjust the placement in the parent
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(pixelWidth , RelativeLayout.LayoutParams.WRAP_CONTENT)
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); // make sure to use the function which takes a boolean value for rules like CENTER_IN_PARENT
homeScreen.setLayoutParams(params); // Add these parameters to the textview

// Let the layout know about your newly created textview so that it can re-draw its canvas
homeScreenLayout.addView(homeScreen);

}
}

As a note, I will add that a of what you're doing can be done in the XML with relative ease, but since you asked about setting it programmatically specifically, I won't go into detail on that aspect. But if you're interested in some structured resources, I would recommend checking out the Android Developer Guide, specifically the section on XML layouts and how they interact with Activities

EDIT: Note the changes I made to the code for the Activity. The major pieces are first inflating the empty RelativeLayout xml with setContentView(int id), and then adding the other TextView to the given layout. There was a minor error in the code I presented concerning the CENTER_IN_PARENT line. According to the [docs](https://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#addRule(int, int)), you must use the addRule(int, int) version of the function when adding rules that use a boolean value.

Add views programmatically in a layout and clustered to the center

From what I have understood, you don't need to set gravity to the LinearLayout childs. Just set

android:layout_centerVertical="true"

on the LinearLayout itself (with height = wrap_content, and vertical orientation). Something like:

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_alignParentLeft="true"
android:layout_centerVertical="true"

android:gravity="center_vertical"
android:orientation="vertical">

Programmatically (though untested):

LinearLayout linearLayout = new LinearLayout(context);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.CENTER_VERTICAL);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER_VERTICAL); //not sure it's needed
linearLayout.setLayoutParams(params);

The linear layout rule will not propagate to its childs: LL will have equally spaced childs. But we set height to wrap_content so it's gonna be exactly that tall, and we set center_vertical so it's gonna stay centered.



Related Topics



Leave a reply



Submit