我有一個列表視圖,它從數據庫中帶來數字。我需要將這些數字相乘並從我的列表視圖中獲得所有數字的總和。但問題是,我必須設置總數的TextView在主要活動中,而不是在適配器上。我如何將總數從適配器發送到主要活動? 我有使用裝載機嗎?ListView適配器和MainActivity
我有這樣的ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter{
public ArrayList<HashMap<String, String>> list;
Activity activity;
int contador = 0;
public ListViewAdapter(Activity activity, ArrayList<HashMap<String, String>> list){
super();
this.activity = activity;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
TextView name;
TextView marc, cant, prec;}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null){
convertView = inflater.inflate(R.layout.list_colum, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.marc = (TextView) convertView.findViewById(R.id.marc);
holder.cant = (TextView) convertView.findViewById(R.id.cant);
holder.prec = (TextView) convertView.findViewById(R.id.prec);
convertView.setTag(holder);
}
else{
holder=(ViewHolder) convertView.getTag();
}
HashMap<String, String> map = list.get(position);
holder.name.setText(map.get(FIRST_COLUMN));
holder.marc.setText(map.get(SECOND_COLUMN));
holder.prec.setText(map.get(THIRD_COLUMN));
holder.cant.setText(map.get(FOURTH_COLUMN));
return convertView;
}
而這MainActivity
public class MAinActivity extends AppCompatActivity {
private ArrayList<HashMap<String, String>> list;
HashMap<String, String> temp = new HashMap<String, String>();
private Button scanBtn;
private TextView total;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<HashMap<String, String>>();
setContentView(R.layout.MainActivity);
total = (TextView)findViewById(R.id.total); //this is the TextView where I have to put the result coming from the adapter.
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
listView = (ListView)findViewById(R.id.listacompras);
ListViewAdapter adapter = new ListViewAdapter(this,list);
listView.setAdapter(adapter);
}
使用broadcastReceiver。 –