Android应用程序-使用setText过程的循环来填充EditText



尝试使用循环设置数据库查询中12个复选框的文本。想用数组值替换"add1",并循环遍历所有12个,而不是拼写每个。有什么办法吗?

这是我试图修改的代码:

add1Text= (CheckBox) findViewById(R.id.add1);
if (cursor.getString(cursor.getColumnIndex("add1")) == null) {
    add1Text.setVisibility(View.GONE);
}
else {
    add1Text.setText(cursor.getString(cursor.getColumnIndex("add1")));
}

请注意:下面的所有内容都超出了我的想象,我现在无法测试。等我有机会的时候再测试

我认为您需要跟踪与每个复选框关联的列。。。我推测是这样的:

列:add1=>复选框:add1Text列:add2=>复选框:add2Text等等。

在这种情况下,您需要手动跟踪它们,可能是在一个数组中。我建议制作一个你可以使用的Pair类。我修改了这篇文章中的类[AJava值对集合?(元组?)]

  public class Pair<L,R> {
  private final L left;
  private final R right;
  public Pair(L left, R right) {
    this.left = left;
    this.right = right;
  }
  public L getLeft() { return left; }
  public R getRight() { return right; }
  @Override
  public int hashCode() { return left.hashCode() ^ right.hashCode(); }
  @Override
  public boolean equals(Object o) {
    if (o == null) return false;
    if (!(o instanceof Pair)) return false;
    Pair pairo = (Pair) o;
    return this.left.equals(pairo.getLeft()) &&
           this.right.equals(pairo.getRight());
  }
}

现在,您需要制作一个包含所需配对的列表(或类似列表)。

List<Pair<CheckBox, String>> list = new ArrayList<Pair<CheckBox, String>>;
list.add(new Pair<CheckBox, String>((CheckBox) findViewById(R.id.add1), "add1");   
list.add(new Pair<CheckBox, String>((CheckBox) findViewById(R.id.add2), "add2");
list.add(new Pair<CheckBox, String>((CheckBox) findViewById(R.id.add3), "add3");

等等

然后,您可以使用类似的东西迭代列表

foreach (Pair<CheckBox, String> item in list)
{
    if (cursor.getString(cursor.getColumnIndex(item.getLeft()) == null)
    {
        item.getRight().setVisibility(View.GONE);
    }
    else
    {
        item.getRight().setText(cursor.getString(cursor.getColumnIndex(item.getLeft()));
    }
}

明白了!忘记了我在处理对象,也意识到我需要第三个数组。以下是我的想法。

  • cList包含列名
  • fList是对象(在本例中为复选框)
  • pList是我从布局中选择的对象的名称。

    Object fList[]={add1Text,add2Text,add3Text};
    int pList[]={R.id.add1,R.id.add2,R.id.add3};
    cList = cursor.getColumnNames();
    for (int i =0; i < fList.length; i++){
        fList[i] = (CheckBox) findViewById(pList[i]);
        if (cursor.getString(cursor.getColumnIndex(cList[i])) == null) {
            ((TextView) fList[i]).setVisibility(View.GONE);
        }
        else {
            ((TextView) fList[i]).setText(cList[i] + " - " + cursor.getString(cursor.getColumnIndex( cList[i])));
        }
    }
    

将复选框文本设置为(列名-值)

最新更新