Add and Remove Views in Android Dynamically?
ViewParent
s in general can't remove views, but ViewGroup
s can. You need to cast your parent to a ViewGroup
(if it is a ViewGroup
) to accomplish what you want.
For example:
View namebar = View.findViewById(R.id.namebar);
((ViewGroup) namebar.getParent()).removeView(namebar);
Note that all Layout
s are ViewGroup
s.
How to remove dynamically created views on button click
Try following code.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
LinearLayout linearParent = (LinearLayout) v.getParent().getParent();
LinearLayout linearChild = (LinearLayout) v.getParent();
linearParent.removeView(linearChild);
}
});
Explanation
- Here first take "GrandParent" of any view.
- Then take its "Parent" view
- With reference to "GrandParent" remove that "Parent" view.
- this will remove all views which that "Parent" holds. As per your code, your "ll" will be "linearChild" here. And "ly" will be "linearParent" here. So whole "ll" will be removed from "ly" which you have added dynamically.
Add & delete view from Layout
I've done it like so:
((ViewManager)entry.getParent()).removeView(entry);
Dynamically add/remove the same xml view
If you remove view
((ViewGroup)indexLayout.getParent()).removeView(indexLayout)
Than you cant get it back !! you have to add it agin if you want to use it
Try to add View if null
private void displayIndex() {
indexLayout = (LinearLayout)v.findViewById(R.id.side_index);
if(indexLayout==null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(getContext().LAYOUT_INFLATER_SERVICE);
View mView = inflater.inflate(R.layout.your_view_having_indexLayout , null, false);
indexLayout =(LinearLayout)mView.findViewById(R.id.side_index);
}
List<String> indexList = new ArrayList<>(mapIndex.keySet());
TextView textView;
for (String index : indexList) {
textView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.alphabet_indicator, null);
textView.setText(index);
textView.setOnClickListener(this);
indexLayout.addView(textView);
}
}
How to dynamically add and delete view in android
- Use a ListView for displaying the list of patterns
Create a custom layout for each list item. e.g.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="555*" />
<TextView
android:id="@+id/textView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="matched 5 " />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" />
</LinearLayout>Create a Custom Adapter class extending BaseAdapter
- It can maintain a list for the patterns to be shown
- In the getView method of the custom adapter -
- inflate the xml
- set the information (like pattern and number of matches) based on the index parameter, using the list
- set onclick listener for the button (delete that item from list and call notifyDatasetInvalidated())
- return the view.
- On "Add Number" add item to the list in the adapter
Android - Dynamically Add Views into View
Use the LayoutInflater
to create a view based on your layout template, and then inject it into the view where you need it.
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);
// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");
// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
You may have to adjust the index where you want to insert the view.
Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT
, or MATCH_PARENT
, etc.
Remove layout on a button click programmatically in android studio
Using RecyclerView with Adapter is your best bet in these situations. My working code is as followes
Class listAdapter
package com.akshita.recycler;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class listAdapter extends RecyclerView.Adapter<listAdapter.ViewHolder> {
private ArrayList<String> product_name;
private ArrayList<Integer> quantity;
private ArrayList<Double> price;
private ArrayList<String> specs;
private static Context scontext;
public listAdapter(Context context)
{
scontext = context;
this.product_name = new ArrayList<String>();
this.price = new ArrayList<Double>();
this.quantity = new ArrayList<Integer>();
this.specs = new ArrayList<String>();
}
public listAdapter(Context context, ArrayList<String> pdname, ArrayList<Integer> quantity, ArrayList<Double> price, ArrayList<String> specs)
{
this.product_name = pdname;
this.price = price;
this.quantity = quantity;
this.specs = specs;
scontext = context;
}
@NonNull
@Override
public listAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem = layoutInflater.inflate(R.layout.productview,parent,false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull listAdapter.ViewHolder holder, int position) {
holder.actv.setText(product_name.get(position));
holder.qty.setText(quantity.get(position).toString());
holder.price.setText(price.get(position).toString());
holder.desc.setText(specs.get(position));
}
public void addView(String pdname, Double prc, Integer quant, String spec ) {
product_name.add(pdname);
quantity.add(quant);
price.add(prc);
specs.add(spec);
notifyItemInserted(product_name.size());
notifyItemInserted(quantity.size());
notifyItemInserted(price.size());
notifyItemInserted(specs.size());
}
public void removeAt(int position) {
product_name.remove(position);
quantity.remove(position);
price.remove(position);
specs.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, product_name.size());
notifyItemRangeChanged(position, quantity.size());
notifyItemRangeChanged(position, price.size());
notifyItemRangeChanged(position, specs.size());
}
@Override
public int getItemCount() {
return product_name.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public AutoCompleteTextView actv;
public EditText qty;
public EditText price;
public EditText desc;
public Button button;
public ViewHolder(View itemView) {
super(itemView);
this.actv = itemView.findViewById(R.id.tv_product);
this.qty = itemView.findViewById(R.id.prod_qty);
this.price = itemView.findViewById(R.id.prod_price);
this.desc = itemView.findViewById(R.id.prod_specs);
this.button = itemView.findViewById(R.id.btn_rmv);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.equals(button)){
removeAt(getAdapterPosition());
}
}
}
}
My Main Class
MainActivity.java
package com.akshita.recycler;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
listAdapter adapter;
RecyclerView hs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hs = findViewById(R.id.rcview);
hs.setHasFixedSize(false);
hs.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
}
@Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.add: addView(v);
}
}
public void addView(View v)
{
if(adapter == null) {
adapter = new listAdapter(this);
hs.setAdapter(adapter);
}
adapter.addView("Name",0.0, 0, "Specs");
}
}
productview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/ll_out"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5sp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10sp"
android:orientation="horizontal">
<AutoCompleteTextView
android:id="@+id/tv_product"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:gravity="left"
android:hint="Enter Product"
android:inputType="text" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10sp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:orientation="vertical">
<EditText
android:id="@+id/prod_qty"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:focusable="true"
android:focusableInTouchMode="true"
android:hint="Enter Quantity"
android:gravity="left"
android:inputType="number" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:orientation="vertical">
<EditText
android:id="@+id/prod_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:hint="Prod Price"
android:gravity="left"
android:inputType="none" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:orientation="vertical">
<EditText
android:id="@+id/prod_specs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:gravity="left"
android:hint="Prod Specs"
android:inputType="none" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:layout_marginTop="1dp"
android:padding="0dp">
<Button
android:id="@+id/btn_rmv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Remove Product"
android:textColor="@color/white" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
activity_main.xml
<?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"
tools:context=".MainActivity"
android:gravity="center|top"
android:orientation="vertical">
<Button
android:id="@+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addView"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_marginTop="10dp"
android:id="@+id/rcview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Whole working code is available here on GitHub
Related Topics
Passing Data Between Fragments to Activity
Strange Behavior with Android Orientation Sensor
Recommended Way/Order to Read Data from a Webservice, Parse That Data and Insert It in a SQLite Db
Sync Data Between Android App and Webserver
What Is an Android Pendingintent
How to Programmatically Open the Permission Screen for a Specific App on Android 6.0 (Marshmallow)
What to Use Instead of "Addpreferencesfromresource" in a Preferenceactivity
How to Make a Dotted/Dashed Line in Android
How to Debug JavaScript on Android
How to Hide a Menu Item in the Actionbar
How to Convert Image File Data in a Byte Array to a Bitmap
How Set Spannable Object Font with Custom Font
Android, Canvas: How to Clear (Delete Contents Of) a Canvas (= Bitmaps), Living in a Surfaceview
What Is Different Between Mainactivity.This VS Getapplicationcontext()
Retrofit 2: Get JSON from Response Body