標籤: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()的作用