标签:
3.使用Activity和Delegate与适配器交互
这个内容是从书里看到的,通过委托模式帮助开发者把所有的业务逻辑从适配器中移到Activity中。下面是添加电话号码的例子,列表中每一行都有一个remove按钮,用于删除电话号码,在适配器中实现“Remove”按钮的点击处理器,但是,并不在适配器中实现删除对象的方法,我们通过一个委托接口调用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显示在屏幕上的时候才作为委托对象使用。
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/max1198/article/details/47067825