使用 for activity:
ViewHelper helper = new ViewHelper(MainActivity.this);
helper.id(R.id.text_view).text("hello world");
helper.id(R.id.button).clicked(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
helper.id(R.id.image_view).image("http://www.xxxxx.com/xxx.png");
使用 for view:
View view = LayoutInflater.from(getContext()).inflate(R.layout.view, null);
ViewHelper helper = new ViewHelper(view);
helper.id(R.id.text_view).text("hello world");
helper.id(R.id.button).clicked(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
helper.id(R.id.image_view).image("http://www.xxxxx.com/xxx.png");
ViewHelper.java 源码
public class ViewHelper {
private View root;
private View view;
private Activity act;
public ViewHelper(View view) {
this.root = view;
this.view = view;
}
public ViewHelper(Activity activity) {
this.act = activity;
}
public ViewHelper id(int id) {
this.view = findView(id);
return this;
}
private View findView(int id) {
View result = null;
if (root != null) {
result = root.findViewById(id);
} else if (act != null) {
result = act.findViewById(id);
}
return result;
}
public ViewHelper text(CharSequence text) {
if (view instanceof TextView) {
TextView tv = (TextView) view;
tv.setText(text);
}
return this;
}
public ViewHelper clicked(View.OnClickListener listener) {
if (view != null) {
view.setOnClickListener(listener);
}
return this;
}
public ViewHelper image(String uri) {
return image(uri, null);
}
public ViewHelper image(String uri, DisplayImageOptions options) {
if (view instanceof ImageView) {
ImageView iv = (ImageView) view;
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(uri, iv, options);
}
return this;
}
}
原文:http://my.oschina.net/oldfeel/blog/403662