删除嵌套线性布局内的视图

时间:2017-11-03 19:32:44

标签: java android android-linearlayout

我编写了以下应用程序,其中显示了一个3乘4的按钮网格。通过在父线性布局内嵌套线性布局来绘制网格。我试图通过引用其ID来删除第一个按钮。但是,android studio表示removeViewAt方法无法解决。有人能告诉我删除其中一个按钮的正确方法吗?谢谢。

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);
    }

1 个答案:

答案 0 :(得分:1)

方法getChildAt(int index)会返回View个对象 您应该将其强制转换为ViewGroup(或其子类之一),以便使用方法removeViewAt(int index)

((LinearLayout) linearLayout.getChildAt(0)).removeViewAt(0)