【问题标题】:How to delete only delete button from the viewgroup in this example在此示例中,如何从视图组中仅删除删除按钮
【发布时间】:2016-08-28 10:48:38
【问题描述】:

我正在学习为 android 编写代码。我从谷歌开发者网站上看到了一个示例应用程序。这基本上是每当用户点击右上角的+ 按钮时,它会在frame layout 中添加一个view group。该视图组包含一个text View 和一个button,如果您单击此按钮(我们将其命名为X 按钮),它将从frame layout 中删除viewgroup。所以他们实现了一个带有视图组和框架布局的列表视图。

代码如下:

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

现在我要做的是当用户单击 X 按钮时不删除整个视图组,而只删除 X 按钮本身。

我正在这样做,但它不起作用:

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

如果有人能告诉我我做错了什么:(

【问题讨论】:

    标签: java android xml android-studio viewgroup


    【解决方案1】:

    我建议隐藏该视图,而不是删除该视图。

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

    但是,如果您想删除该视图,则操作正确,但您需要刷新/使添加了delete_button 的视图无效,即mContainerView.invalidate()

    【讨论】:

    • 感谢RRR的建议,但我想删除它:) 如何刷新无效的mContainerView?
    • 我已经尝试过 mContainerView.invalidate();但什么也没发生。
    猜你喜欢
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2018-12-17
    • 2018-11-25
    • 2020-03-25
    相关资源
    最近更新 更多