ListView优化总结(二)--Android
3.使用Activity和Delegate与适配器交互
这个内容是从书里看到的,通过托付模式帮助开发人员把全部的业务逻辑从适配器中移到Activity中。
以下是加入电话号码的样例,列表中每一行都有一个removebutton,用于删除电话号码,在适配器中实现“Remove”button的点击处理器,可是。并不在适配器中实现删除对象的方法,我们通过一个托付接口调用Activity的方法删除对象。
适配器的代码:
public class NumbersAdapter extends ArrayAdapter<Integer> {
public static interface NumbersAdapterDelegate { //定义托付接口
void removeItem(Integer value);
}
private LayoutInflater mInflator;
private NumbersAdapterDelegate mDelegate;
public NumbersAdapter(Context context, List<Integer> objects) {
super(context, 0, objects);
mInflator = LayoutInflater.from(context);
}
@Override
public View getView(int position, View cv, ViewGroup parent) {
if (null == cv) {
cv = mInflator.inflate(R.layout.number_row, parent, false);
}
final Integer value = getItem(position);
TextView tv = (TextView) cv.findViewById(R.id.numbers_row_text);
tv.setText(value.toString());
View button = cv.findViewById(R.id.numbers_row_button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (null != mDelegate) {
mDelegate.removeItem(value); //删除对象
}
}
});
return cv;
}
public void setDelegate(NumbersAdapterDelegate delegate) { //为适配器设置托付对象
mDelegate = delegate;
}
}
Activity的代码:
public class MainActivity extends Activity implements
NumbersAdapter.NumbersAdapterDelegate { //实现NumbersAdapterDelegate接口
private static final String TAG = MainActivity.class
.getCanonicalName();
private ListView mListView;
private ArrayList<Integer> mNumbers;
private NumbersAdapter mAdapter;
private EditText mEditText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mEditText = (EditText) findViewById(R.id.main_edittext);
mListView = (ListView) findViewById(R.id.main_listview);
mNumbers = new ArrayList<Integer>();
mAdapter = new NumbersAdapter(this, mNumbers);
mListView.setAdapter(mAdapter);
}
@Override
protected void onResume() {
super.onResume();
mAdapter.setDelegate(this); //在onResume方法中注冊托付对象
}
@Override
protected void onPause() {
super.onPause();
mAdapter.setDelegate(null); //在onPause方法中取消注冊托付对象
}
@Override
public void removeItem(Integer value) { //从列表中移除指定项,然后通知适配器绑定的数据发生变化
mNumbers.remove(value);
Toast
.makeText(this, "Removed object: " + value, Toast.LENGTH_SHORT)
.show();
mAdapter.notifyDataSetChanged();
}
public void addNumber(View v) {
String value = mEditText.getText().toString().trim();
try {
mNumbers.add(Integer.valueOf(value));
mEditText.setText("");
mAdapter.notifyDataSetChanged();
} catch (NumberFormatException e) {
Log.e(TAG, "Couldn't convert to integer the string: " + value);
}
}
}
没有在onCreate方法中设置托付对象,而在onResume方法中设置托付对象。目的是为了确保仅仅在Activity显示在屏幕上的时候才作为托付对象使用。