通过代码生成ImageView,并把它添加到布局中来时,可能会遇到setId()方法,那么它有什么作用?
作用如下:
通过代码添加ImageView、TextView等控件时,有时候会用到RelativeLayout.LayoutParams等布局的addRule()方法,如下代码:
ImageView imageView = new ImageView(this.getActivity()); imageView.setId(View.generateViewId()); ... params.addRule(RelativeLayout.BELOW, imageView.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;
原文:http://blog.csdn.net/adayabetter/article/details/45038897