【问题标题】:Dynamically adding and removing mapped buttons to a TableLayout向 TableLayout 动态添加和删除映射按钮
【发布时间】:2019-06-03 17:18:07
【问题描述】:

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

所以我目前有一个包含一个整数和一个对象的 HashMap。它也会随着用户的需要而更新。当用户按下“添加项目”按钮时,我希望它完成将项目添加到 HashMap 的动作,然后更新我的 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 已删除所有包含的视图。 5) 如果 mLayoutProjects.getChildCount() 等于 0 或 i % 2 等于 0 则: 创建新行并将其添加到 mLayoutProjects。 6) 在行中添加一个项目按钮。

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

【问题讨论】:

    标签: java android android-studio


    【解决方案1】:

    更新:

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

    所以我将所有内容都更改为 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;
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 2012-07-28
      • 1970-01-01
      相关资源
      最近更新 更多