我正在尝试将动态复选框文本传递给下一个活动。我想通过ID遍历复选框并查看它们是否已被选中。如果是,我想从复选框中取出文本并将其连接到一个字符串上。当我运行它时,应用程序崩溃了。我知道这是因为意图。这是一个快速,简单的学校截止日期修复 - 任何帮助将不胜感激。
编辑:对addtocart()方法进行了一些更改,仍然无效。
public class SearchResultsActivity extends Activity {
public int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
Intent intent = getIntent();
String results = intent.getStringExtra("key");
if (results.equals("No results")) {
//do nothing
} else {
List<String> list = new ArrayList<String>(Arrays.asList(results.split("-")));
count = list.size() / 3;
//puthere.setText(list.get(0));
LinearLayout linear = (LinearLayout) findViewById(R.id.horizontal_ll);
int isbn = 1;
int title = 0;
int price = 2;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
for (int i = 0; i < count; i++) {
CheckBox checkBox = new CheckBox(this);
checkBox.setText("Title: " + list.get(isbn) + ", ISBN: " + list.get(title) + ", Price: " + list.get(price));
checkBox.setId(i);
checkBox.setLayoutParams(params);
linear.addView(checkBox);
isbn = isbn + 3;
title = title + 3;
price = price + 3;
}
}
}
public void addtocart(View v) {
String checked = "";
ViewGroup viewgroup=(ViewGroup) v.getParent();
int count = viewgroup.getChildCount();
for (int i = 0; i < count; i++) {
Object child = viewgroup.getChildAt(i);
if (child instanceof CheckBox) {
CheckBox checkboxchild = (CheckBox) child;
if(checkboxchild.isChecked()) {
String text = checkboxchild.getText().toString();
checked = checked+"-"+text;
}
}
Intent intent_name = new Intent(this, CheckOutActivity.class);
intent_name.putExtra("somethingnew", checked);
this.startActivity(intent_name);
}
}
public void test(View v) {
}
}
答案 0 :(得分:0)
您可能应首先阅读有关视图ID如何在Android上运行的信息。您不能在for循环中循环遍历增量viewIds;它不起作用。
循环的一种可能方法是:
ViewGroup viewgroup=(ViewGroup) view.getParent();
int count = viewgroup.getchildcount();
for (int i = 0; i < count; i++) {
if (viewGroup.getChildAt(i) instanceOf Checkbox) {
if (((Checkbox) viewGroup.getChildAt(i)).isChecked()) {
...
}
}
}
强烈建议您先阅读有关视图如何在Android中运行的文档。