Android之 ImageView中setId()的作用

來源:互聯網
上載者:User

標籤:android

 通過代碼產生ImageView,並把它添加到布局中來時,可能會遇到setId()方法,那麼它有什麼作用?

作用如下:

通過代碼添加ImageView、TextView等控制項時,有時候會用到RelativeLayout.LayoutParams等布局的addRule()方法,如下代碼:

ImageView imageView = new ImageView(this.getActivity());imageView.setId(View.generateViewId());...params.addRule(RelativeLayout.BELOW, imageView.getId());

此時就能知道setId()的作用了。就是在某控制項的下方、上方等用到具體View的地方,需要getId().

另附上一塊完整的代碼,但是沒setId(),ImageView沒有ID,直接取會造成錯誤。

 

RelativeLayout layout = new RelativeLayout(this.getActivity());    layout.setLayoutParams(new RelativeLayout.LayoutParams(             LayoutParams.FILL_PARENT,             LayoutParams.FILL_PARENT));    layout.setBackgroundColor(Color.parseColor("#CCCDCDCD"));    ImageView imageView = new ImageView(this.getActivity());    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);    params.addRule(RelativeLayout.CENTER_IN_PARENT);    imageView.setLayoutParams(params);    imageView.setBackgroundResource(R.drawable.create_template);    AnimationDrawable frameAnimation = (AnimationDrawable) imageView.getBackground();    if (frameAnimation != null) {        frameAnimation.start();    }    TextView textView = new TextView(this.getActivity());    params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);    params.addRule(RelativeLayout.BELOW, imageView.getId());    textView.setLayoutParams(params);    textView.setText("Generating information...");    layout.addView(imageView);    layout.addView(textView);    return layout;

Android之 ImageView中setId()的作用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.