摘要:我需要一種方法來我的主要活動範圍內的觸發我的計算()函數,當一個項目被添加或從我的ListView刪除如何從mainactivity檢測的ListView變化
背景: 我Android應用程序使用列表項填充列表視圖。一個列表項包含一個textview和一個imagebutton(刪除),在點擊時從列表中刪除該項目。我使用自定義適配器來跟蹤列表中的更改。這一切工作正常。
在我的主要活動中,一些計算基於名爲calulate()的函數在列表中的值進行。無論何時從列表中添加或刪除項目,我都想調用此函數。但是,我不知道這是否可行,以及如何實現這樣的功能。
我注意到有可能使用registerDataSetObserver()添加一個觀察者,當notifyDataSetChanged()被調用時會被通知。但是,我不確定這是否是我需要的,以及如何實現這一點。任何幫助或建議都是值得歡迎的。
這裏是我的CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
static final String TAG = "CustomListAdapter";
private Context context;
ArrayList <String> listArray;
LayoutInflater inflater;
public CustomListAdapter(Context context, List <String> inputArray) {
super();
this.context = context;
this.listArray = (ArrayList<String>) inputArray;
}
@Override
public int getCount() {
return listArray.size(); // total number of elements in the list
}
@Override
public String getItem(int i) {
return listArray.get(i); // single item in the list
}
@Override
public long getItemId(int i) {
return i; // index number
}
@Override
public View getView(int position, View convertView, final ViewGroup parent) {
View V = convertView;
if(V == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
V = vi.inflate(R.layout.selected_drug_list_item, null);
}
//place text in textview
String listItem = listArray.get(position);
TextView textView = (TextView) V.findViewById(R.id.selectedDrugName);
textView.setText(listItem);
ImageButton deleteSelectedDrugButton = (ImageButton) V.findViewById(R.id.deleteSelectedDrugButton);
deleteSelectedDrugButton.setTag(position);
//Listener for the delete button. Deletes item from list.
deleteSelectedDrugButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
//re
Integer index = (Integer) view.getTag();
listArray.remove(index.intValue());
notifyDataSetChanged();
}
});
return V;
}
public void add(String input) {
listArray.add(input);
notifyDataSetChanged();
Log.v(TAG, input + " added to list");
}
public void remove(String input){
listArray.remove(input);
notifyDataSetChanged();
Log.v(TAG, input + " added to list");
}
}
這裏是我的ListView是如何在我的onCreate()方法進行初始化。
selectionListView = (ListView) findViewById(R.id.selectionListView);
selectionAdapter = new CustomListAdapter(this,myListItems);
selectionListView.setAdapter(selectionAdapter);
如果需要其他代碼片段,我會很樂意提供它。
像夢一樣工作,非常感謝! –
這真的很有幫助,節省我的時間。謝謝! –