1

I wrote the following application where a 3 by 4 grid of buttons are displayed. The grid is drawn by nesting linearlayouts inside a parent linearlayout. I'm trying to delete the first button by referring to its id. However, android studio says that removeViewAt method cannot be resolved. Can anyone tell me the correct way to delete one of the buttons please? Thank you.

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

    private static final int MENU_ITEM_ITEM1 = 1;
    LinearLayout.LayoutParams params;
    LinearLayout linearLayout;
    int _row;
    int column;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);  //Can also be done in xml by android:orientation="vertical"
        params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        params.weight = 1.0f;
        params.gravity = Gravity.TOP;
        //layout.setBackgroundColor(0xFFFFFFFF);
        _row=3;
        column=4;
        update();

        (linearLayout.getChildAt(0)).removeViewAt(0);
    }


    public void update(){
        for (int i = 0; i < _row; i++) {
            LinearLayout row = new LinearLayout(this);
            row.setLayoutParams(params);

            for (int j = 0; j < column; j++) {
                Button btnTag = new Button(this);
                btnTag.setLayoutParams(params);
                btnTag.setText("Button " + (j + 1 + (i * column)));
                btnTag.setId(j + 1 + (i * column));
                if ((i+j) % 2 == 0) {
                    btnTag.setBackgroundColor(0xFFFF0000);
                } else {
                    btnTag.setBackgroundColor(0x00000000);
                }
                btnTag.setBackgroundResource(R.drawable.ic_android_black_24dp);
                row.addView(btnTag);
            }
            linearLayout.addView(row);
        }

        setContentView(linearLayout);
    }
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Christian Temple
  • 121
  • 1
  • 1
  • 7

1 Answers1

1

The method getChildAt(int index) returns a View object.
You should cast it to ViewGroup (or one of its sub-classes) in order to use the method removeViewAt(int index):

((LinearLayout) linearLayout.getChildAt(0)).removeViewAt(0)
Juan Cruz Soler
  • 8,172
  • 5
  • 41
  • 44