我正试图以编程方式设置LayoutParams.BELOW
。这里是我的代码:
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;
但位置不对。你知道为什么位置不好吗?
最佳答案
ImageView
没有ID。您需要给它一个ID。定义一些常量整数值,或使用View.generateViewId()
,并在布局参数中使用它之前调用setId()
:
ImageView imageView = new ImageView(this.getActivity());
imageView.setId(View.generateViewId());
...
params.addRule(RelativeLayout.BELOW, imageView.getId());