Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add and Remove Views in Android Dynamically?

People also ask

Can we add or delete any view type in XML on runtime?

Yes, because you can not add/delete any View Type in XML on runtime. Dynamic layouts are developed using Java and can be used to create layouts that you would normally create using an XML file.

How do you delete a view in linear layout?

Simply Use linearLayout. removeView(View view); It would refresh automaically.

How do I remove an inflated view?

Just like you added views, you can remove them. Just call removeViewAt(int index) or removeView(View view) on the parent container to remove the view(s) you want. Alternatively, if you foresee reusing them, you can just set their visibility to GONE .


ViewParents in general can't remove views, but ViewGroups 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 Layouts are ViewGroups.


I need the exact same feature described in this question. Here is my solution and source code: https://github.com/laoyang/android-dynamic-views. And you can see the video demo in action here: http://www.youtube.com/watch?v=4HeqyG6FDhQ

Layout

Basically you'll two xml layout files:

  • A horizontal LinearLayout row view with a TextEdit, a Spinner and an ImageButton for deletion.
  • A vertical LinearLayout container view with just a Add new button.

Control

In the Java code, you'll add and remove row views into the container dynamically, using inflate, addView, removeView, etc. There are some visibility control for better UX in the stock Android app. You need add a TextWatcher for the EditText view in each row: when the text is empty you need to hide the Add new button and the delete button. In my code, I wrote a void inflateEditRow(String) helper function for all the logic.

Other tricks

  • Set android:animateLayoutChanges="true" in xml to enable animation
  • Use custom transparent background with pressed selector to make the buttons visually the same as the ones in the stock Android app.

Source code

The Java code of the main activity ( This explains all the logic, but quite a few properties are set in xml layout files, please refer to the Github source for complete solution):

public class MainActivity extends Activity {
// Parent view for all rows and the add button.
private LinearLayout mContainerView;
// The "Add new" button
private Button mAddButton;
// There always should be only one empty row, other empty rows will
// be removed.
private View mExclusiveEmptyView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.row_container);
    mContainerView = (LinearLayout) findViewById(R.id.parentView);
    mAddButton = (Button) findViewById(R.id.btnAddNewItem);

    // Add some examples
    inflateEditRow("Xiaochao");
    inflateEditRow("Yang");
}

// onClick handler for the "Add new" button;
public void onAddNewClicked(View v) {
    // Inflate a new row and hide the button self.
    inflateEditRow(null);
    v.setVisibility(View.GONE);
}

// onClick handler for the "X" button of each row
public void onDeleteClicked(View v) {
    // remove the row by calling the getParent on button
    mContainerView.removeView((View) v.getParent());
}

// Helper for inflating a row
private void inflateEditRow(String name) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.row, null);
    final ImageButton deleteButton = (ImageButton) rowView
            .findViewById(R.id.buttonDelete);
    final EditText editText = (EditText) rowView
            .findViewById(R.id.editText);
    if (name != null && !name.isEmpty()) {
        editText.setText(name);
    } else {
        mExclusiveEmptyView = rowView;
        deleteButton.setVisibility(View.INVISIBLE);
    }

    // A TextWatcher to control the visibility of the "Add new" button and
    // handle the exclusive empty view.
    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

            // Some visibility logic control here:
            if (s.toString().isEmpty()) {
                mAddButton.setVisibility(View.GONE);
                deleteButton.setVisibility(View.INVISIBLE);
                if (mExclusiveEmptyView != null
                        && mExclusiveEmptyView != rowView) {
                    mContainerView.removeView(mExclusiveEmptyView);
                }
                mExclusiveEmptyView = rowView;
            } else {
                if (mExclusiveEmptyView == rowView) {
                    mExclusiveEmptyView = null;
                }
                mAddButton.setVisibility(View.VISIBLE);
                deleteButton.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
        }
    });

    // Inflate at the end of all rows but before the "Add new" button
    mContainerView.addView(rowView, mContainerView.getChildCount() - 1);
}

This is my general way:

View namebar = view.findViewById(R.id.namebar);
ViewGroup parent = (ViewGroup) namebar.getParent();
if (parent != null) {
    parent.removeView(namebar);
}

Hi You can try this way by adding relative layout and than add textview in that.

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            (LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT));

RelativeLayout relative = new RelativeLayout(getApplicationContext());
relative.setLayoutParams(lp);

TextView tv = new TextView(getApplicationContext());
tv.setLayoutParams(lp);

EditText edittv = new EditText(getApplicationContext());
edittv.setLayoutParams(lp);

relative.addView(tv);
relative.addView(edittv);

Just use myView.setVisibility(View.GONE); to remove it completely. But if you want to reserve the occupied space inside its parent use myView.setVisibility(View.INVISIBLE);


ViewGroup class provides API for child views management in run-time, allowing to add/remove views as well.

Some other links on the subject:

Android, add new view without XML Layout

Android Runtime Layout Tutorial

http://developer.android.com/reference/android/view/View.html

http://developer.android.com/reference/android/widget/LinearLayout.html


For Adding the Button

LinearLayout dynamicview = (LinearLayout)findViewById(R.id.buttonlayout);
LinearLayout.LayoutParams  lprams = new LinearLayout.LayoutParams(  LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);

Button btn = new Button(this);
btn.setId(count);
final int id_ = btn.getId();
btn.setText("Capture Image" + id_);
btn.setTextColor(Color.WHITE);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
dynamicview.addView(btn, lprams);
btn = ((Button) findViewById(id_));
btn.setOnClickListener(this);

For removing the button

ViewGroup layout = (ViewGroup) findViewById(R.id.buttonlayout);
View command = layout.findViewById(count);
layout.removeView(command);