【问题标题】:How can I check specific checkboxes on startup?如何在启动时检查特定复选框?
【发布时间】:2017-08-25 06:24:47
【问题描述】:

我正在使用 Android Studio 创建一个使用 java 的应用程序,但我对它相当陌生,我的大部分经验是在 Visual Studio 中使用 C# 和 Winforms。

目前我有一个 ListView,里面有 CheckBoxes,我正在使用 ArrayAdapter 来同步列表。

    ArrayList<String> items = new ArrayList<>();
    items.add("Alpha");
    items.add("Bravo");
    items.add("Charlie");
    items.add("Delta");

    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.row_layout, R.id.chkText, items);
    lv.setAdapter(adapter);

    // Test
    Toast.makeText(getApplicationContext(), "Count " + lv.getAdapter().getCount(), Toast.LENGTH_LONG).show();
    for (int j = 1; j < lv.getAdapter().getCount(); j++)
    {
        CheckBox cb = (CheckBox) lv.getAdapter().getItem(j);
        cb.setChecked(true);
    }

getCount() 确实返回了正确的值,但应用程序在尝试选中这些框时会崩溃。对于这样一个简单的任务,我在网上找到的所有答案似乎都过于复杂了。例如,当应用程序加载时,是否有简单易用的方法可以选中“Bravo”和“Delta”复选框?

【问题讨论】:

  • lv.getAdapter() 返回一个适配器,而不是一个复选框。
  • 丢失了一部分,我的错,现在显示为:lv.getAdapter().getItem(j);

标签: java android listview checkbox


【解决方案1】:

获得该复选框的真正方法需要您深入研究 ListView 子项,而不是适配器本身。

android - listview get item view by position

基本上,适配器只存储数据并将数据“绑定”到视图。适配器本身并不实际保存视图信息。

  • lv.getAdapter() 返回一个通用的、无类型的Adapter&lt;?&gt;

  • 当您执行lv.getAdapter().getItem(j) 时,将返回一个Object,它只能转换为String,因为您使用了ArrayAdapter&lt;String&gt;


解决此问题的更好方法是,如果您创建一个自定义类extends ArrayAdapter&lt;String&gt;,然后您将能够编写自己的字段来存储一个名为mChecked 的布尔列表,例如,以及一个方法更新该列表。

更详细的想法是这样的

private List<Boolean> mChecked = new ArrayList<>();

public void setChecked(int position, boolean checked) {
  mChecked.set(position, checked); // Might throw out of bounds exception! 
  notifyDataSetChanged(); // Need to refresh the adapter
}

public boolean isChecked(int position) {
  return mChecked.get(position);
}

@Override
public void getView( ... ) {
    ...

    View rowView = ... ;

    TextView tv = (TextView) rowView.findViewById(R.id.chkText);
    tv.setText(getItem(position));
    Checkbox cb = (Checkbox) rowView.findViewById(R.id.checkbox);
    cb.setChecked(isChecked(position));
}

适配器类的getView() 方法将控制您何时通过checkBox.setChecked(isChecked(position)); 选中一个框

最后,您不会在应用加载时设置这些框,而是在初始化适配器时设置。

【讨论】:

  • 我想我对 View 的用途感到困惑。在您的第一种方法中,如果我能获得一个视图,那就太棒了,但我该怎么做呢?我似乎无法发现 getChild() 或 getItem() 方法。使用第二种方法,假设我确实创建了一个自定义类,如果我不能使用当前的适配器,我怎么能让 setChecked() 工作?对不起,我对这很多东西都很陌生。一切似乎都倒退了。
  • lv.getChild()。你会得到一些View 对象,然后你必须findViewById 为你在row_layout.xml 中设置的任何复选框ID。对于第二个选项,请参阅此示例guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多