How To Add A View Programmatically In Andriod

This article will make you familar with the coding in android and know how to create views and attach callback listeners to it.

Introduction

Many times we come across a problem in Android, where we need to create a feature of adding a view when a button is pressed, for instance, adding a new EditText view when a add button in a todo list application.

So, today we will go through how to create this feature in an android application. I hope before reading this article, you are familiar with the coding in android and know how to create views and attach callback listeners to it.

Basic Todo App Setup

First create a New Project in android and let's write a basic layout for a todo list having a TextView, LinearLayout and a Button to add more EditText to the todo list.

In this tutorial we will first go through with the code and then explain it step-by-step.

So here is the Layout of the a generic Todo-List

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Todo List"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:textSize="32sp"
android:textColor="@android:color/black"
android:textStyle="bold"/>
<LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

</LinearLayout>
<Button
android:id="@+id/addTaskButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Add Task"/>
</LinearLayout>

​The above Layout code will result as below.


todo_app_screen_img


Layout Code Explanation

So the code in the layout is a simple layout having a root view of Linear Layout having a vertical orientation and three elements in it:

  1. Text View (Lines 10-18)
  2. Linear Layout (Lines 19-25)
  3. Button (Lines 26-31)

Here, the Text View is holding a simple text as "Todo List" and after that, the Empty Linear Layout having id of container, this linear layout is the place where we have to insert the EditText View programmatically, for now let it be empty. And then finally we have our "Add Task" Button to add the EditText in the empty Linear Layout.

Adding Layout Programmatically

So now after creating layout, let's start coding the logic for adding the view (EditText and delet button) to the layout programmatically. Let's first look out the code and then we will break it down and understand it.

Here is the Code for java file.

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Getting LinearLayout having id "Container" and Add Task button from layout.
final LinearLayout container = findViewById(R.id.container);
Button addTask = findViewById(R.id.addTaskButton);

//Adding a onClickListener to the "Add Task" button.
//To add the view to the LinearLayout with id "container".
addTask.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Create the view to add in container

//rootView
LinearLayout l = new LinearLayout(getApplicationContext());
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(dpTopx(10), dpTopx(10), dpTopx(10),dpTopx(10));
l.setLayoutParams(params);
l.setOrientation(LinearLayout.HORIZONTAL);

//EditText view
EditText e = new EditText(getApplicationContext());
LinearLayout.LayoutParams paramsEditText = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
paramsEditText.weight = 1;
e.setLayoutParams(paramsEditText);
e.setHint("Type new Task");

//Image View for close button
final ImageView i = new ImageView(getApplicationContext());
LinearLayout.LayoutParams paramsImgView = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
paramsImgView.weight = 0.15f;
i.setBackground(getResources().getDrawable(R.drawable.close_white_24dp));

//Adding the EditText and Close Button to LinearLayout
l.addView(e);
l.addView(i);

//Adding the Created LinearLayout to Container
container.addView(l);

//Adding OnClick Listener to Close button Image for removing the view
i.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ViewGroup parent = (ViewGroup) i.getParent();
parent.removeAllViews();
if(parent.getParent() != null){
((ViewGroup) parent.getParent()).removeView(parent);
}
}
});
}
});
//Doing a virtual tap to "Add Task" Button
//To create the first EditText View for the Layout
addTask.callOnClick();
}
//Function to convert dp to pixels.
private int dpTopx(int dp){
return (int)(dp * getApplicationContext().getResources().getDisplayMetrics().density);
}
}


Understanding the Code

So in the code, in onCreate method, we firstly fetch the "Container" Linear layout and Add Task Button from the Layout file by using findViewById() function in lines 18-19.

Then in line 23, we attach a onClickListener() to the Add Task Button so that when the Add Task button is clicked the View gets populated after creating the View which we want to add in the "container" LinearLayout

Then in lines 29-34, we create a LinearLayout having with of "match parent" and height of "wrap content", also having margin of "10dp" using a helper method named "dpTopx()" in lines 74-76, and vertical orientation.

Similarly, in lines 37-41, we create a EditText View having width of zero (because we will add weight to it), height as "wrap content", we will add weight = 1 to it and also a placeholder text using setHint()method as "Type new Task".

Also, in lines 44-47, we create a ImageView for holding a close sign acting as a button to delete the view when clicked. This view will have weight of 0.15 and have background set from resource R.drawable.close_white_24dp in ImageView.

Then, in lines 50 and 51 we add the EditText View and ImageView to the previously created LinearLayout.

Then, in line 54, we add the whole LinearLayout to the previously fetch "container" LinearLayout from the Layout file.

And then, we also add a onClickListener() to the ImageView in lines 57-66, so that when it is clicked, we delete the whole layout we created.

And finally, at Line 71, we just virtually tap the "Add Task" button to create the layout and populate it in "container" LinearLayout as soon as the application is opened, so that, it seems that a single View is default to present on screen.

Conclusion

I hope you have now understood how to dynamically add a View in layout and also remove it efficiently in layout. A big thanks if you joined till here and enjoyed the read. Also look at all blog posts here.

Thank you!

Akash Srivastava
Software Engineer @ Seawoods Ventures Inc.
© 2019-2024 dev-akash.in