Kuldeep Kumar
Kuldeep Kumar

Reputation: 925

How to delete only delete button from the viewgroup in this example

I am learning to code for android. I have come across an example app from google developers website. What this basically does is whenever user clicks on the + button on the top right corner, it adds a view group to the frame layout. That view group contains a text View and a button, if you click on this button (lets name it X button) it removes the viewgroup from the frame layout. So they kind of implemented a list view with viewgroup and a framelayout.

Here's the code:

private void addItem() {
        // Instantiate a new "row" view.
        final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(
                R.layout.list_item_example, mContainerView, false);

        // Set the text in the new row to a random country.
        ((TextView) newView.findViewById(android.R.id.text1)).setText(
                COUNTRIES[(int) (Math.random() * COUNTRIES.length)]);

        // Set a click listener for the "X" button in the row that will remove the row.
        newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Remove the row from its parent (the container view).
                // Because mContainerView has android:animateLayoutChanges set to true,
                // this removal is automatically animated.
                switch (view.getId()) {
                    case R.id.delete_button:
                        mContainerView.removeView(newView);
                        break;
                }

                // If there are no rows remaining, show the empty view.
                if (mContainerView.getChildCount() == 0) {
                    findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
                }
            }
        });

        // Because mContainerView has android:animateLayoutChanges set to true,
        // adding this view is automatically animated.

        mContainerView.addView(newView, 0);
    }

Now what I want to do is to not delete the entire viewgroup when user clicks on X Button but to only delete the X button itself.

I am doing it like this but its not working:

mContainerView.removeView(newView.findViewById(R.id.delete_button));

If anyone could tell me what am I doing wrong :(

Upvotes: 0

Views: 59

Answers (1)

Ravi
Ravi

Reputation: 35549

Instead of removing that view, i will suggest to hide that view.

newView.findViewById(R.id.delete_button).setVisibility(View.GONE);

However if you want to delete that view, you are doing it correctly but you need to refresh/invalidate your view in which delete_button is added, i.e. mContainerView.invalidate()

Upvotes: 2

Related Questions