首页 > 移动平台 > 详细

Android之 ImageView中setId()的作用

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

 通过代码生成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()的作用

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!