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

Android之 ImageView中setId()的作用

时间:2015-04-14 13:04:49      阅读:174      评论:0      收藏:0      [点我收藏+]

标签: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()的作用

标签:android

原文地址:http://blog.csdn.net/adayabetter/article/details/45038897

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