android 开发用一行代码操作只使用一次的 view
使用 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; } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。