码迷,mamicode.com
首页 > 移动开发 > 详细

android 开发用一行代码操作只使用一次的 view

时间:2015-04-20 07:06:59      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

使用 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;
    }
}


android 开发用一行代码操作只使用一次的 view

标签:

原文地址:http://my.oschina.net/oldfeel/blog/403662

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!