gpt4 book ai didi

java - 动态添加和删除映射按钮到 TableLayout

转载 作者:行者123 更新时间:2023-11-29 23:22:16 24 4
gpt4 key购买 nike

我正在努力寻找一种在 TableLayout 中添加和删除可点击按钮的好方法。

所以我目前有一个包含整数和对象的 HashMap。它也随着用户的需要而更新。当用户按下“添加项目”按钮时,我希望它完成向 HashMap 添加项目的 Action ,然后更新我的 TableLayout。

我想将每行限制为 2 个按钮。我注意到,在我可以使用添加的新项目更新 TableLayout(或任何布局)之前,我必须删除之前的迭代。

我尝试了多种不同的方法来连续添加和删除按钮,但似乎都没有用。

One example of what I did is:

int i = mProjectMap.size();
for(Map.Entry<Integer, Counter> entry : mProjectMap.entrySet()) { // This already has one entry before reaching this loop
if(i % 2 == 0 || mLayoutProjects.getChildCount() == 0) {
mTableRow = new TableRow(mMainContext);
mLayoutProjects.addView(mTableRow);
}

mTableRow.addView(entry.getValue());
};

As for removing the views I've tried:
mLayoutProjects.removeAllViews();

and:
mLayoutProjects.removeViewsInLayout();

And many more.

应该发生的事情如下:

1) 用户点击“添加项目”按钮。2) 项目填充了相关信息。 (完毕)3)项目添加到mProjectMap(完成)4) mLayoutProjects 已删除所有包含 View 。5) 如果 mLayoutProjects.getChildCount() 等于 0 或 i % 2 等于 0,则:创建新行并将其添加到 mLayoutProjects。6) 在行中添加一个项目按钮。

相反,当我按下“添加项目”按钮时,该循环似乎在第一次迭代时添加了所有内容,但屏幕上没有显示任何按钮(我有一个项目计数器,它递增一次)。然后我再次按下按钮,应用程序崩溃了。

最佳答案

更新:

我已经用不同的方式解决了这个问题。对于那些偶然发现这一点的人,我将包括完整的解决方案:

所以我将所有内容都更改为 LinearLayout 并且在“addProjectButton”函数中我有以下内容:

int i = mProjectMap.size();
for(Map.Entry<Integer, Counter> entry : mProjectMap.entrySet()) {
if((entry.getKey() - 1) % 2 == 0 || mLayoutRow == null) {
mLayoutRow = new LinearLayout(mMainContext);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
mLayoutRow.setOrientation(LinearLayout.HORIZONTAL);
mLayoutRow.setGravity(Gravity.CENTER);
mLayoutRow.setLayoutParams(lp);
mLayoutProjects.addView(mLayoutRow);
}

mLayoutRow.addView(entry.getValue());
}

然后,在我的“removeProjectButton”函数中:

for(Map.Entry<Integer, Counter> entry : mProjectMap.entrySet()) {
if(entry.getValue().getParent() != null) {
((ViewGroup) entry.getValue().getParent().removeView(entry.getValue());
}
}

mLayoutRow = null;

这似乎运行得非常好,没有任何问题......虽然它最终可能好得令人难以置信,但只有时间才能证明一切。

关于java - 动态添加和删除映射按钮到 TableLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54101545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com