android 開發用一行代碼操作只使用一次的 view

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.