我的每个行都有一个带有切换按钮的列表视图。我将已检查开关的总和存储在变量中。在MainActivity中,我启动自定义适配器,我希望得到一些已检查的开关。那么如何将值从自定义适配器传递给父活动?在listview的页脚中,我有一个按钮" Dalej"我在MainActivity中创建它,并希望在用户点击它时从适配器获取值(此总和)?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardio);
String[] cardio_1 = getResources().getStringArray(R.array.cardio_1);
ListView listView = (ListView) findViewById(R.id.listView);
View footer = getLayoutInflater().inflate(R.layout.cardio_footer, null);
listView.addFooterView(footer);
ListAdapter listAdapter = new Adapter_cardio(this, cardio_1);
cardio.addAll(Arrays.asList(cardio_1))
listView.setAdapter(listAdapter);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
});
适配器
public Adapter_cardio(Context context, String[] cardios ) {
super(context, R.layout.cardio_row, cardios);
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Log.d("TAG", "tessst1");
zaznaczone = new ArrayList();
}
public String suma(String sum) {
return sum;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
String pytanie = getItem(position);
if (convertView==null){
convertView = inflater.inflate(R.layout.cardio_row, null);
holder = new ViewHolder();
holder.question = (TextView) convertView.findViewById(R.id.question);
holder.s = (Switch)convertView.findViewById(R.id.switch1);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
holder.question.setText(pytanie);
//Model_cardio question = getItem(position);
//final boolean doCheck = (position == 4) || (position == 5);
holder.s.setTag(position);
holder.s.setOnCheckedChangeListener(null);
if (zaznaczone.contains(position) )
{
holder.s.setChecked(true);
}
else
{
holder.s.setChecked(false);
}
holder.s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
zaznaczone.add((Integer) buttonView.getTag());
} else {
zaznaczone.remove((Integer) buttonView.getTag());
}
}
});
sum = zaznaczone.size();
String x = "2";
Log.d("TAG_Switch_all", "suma = " + sum);
return convertView;
}
答案 0 :(得分:1)
想要在用户点击它时从适配器获取值(此总和)?
创建一个exit
方法,从public
类返回sum
:
Adapter_cardio
并在按钮上调用public int getSum(){
return zaznaczone.size();
}
方法,使用getSum
对象作为:
listAdapter
如果{on}方法中无法访问public void onClick(View v) {
Log.d("TAG_Switch_all", "suma = " + ((Adapter_cardio)listAdapter).getSum());
}
,则将其声明为listAdapter