简体   繁体   English

以编程方式设置LayoutParams.BELOW

[英]Set LayoutParams.BELOW programmatically

I'm trying to set LayoutParams.BELOW programmatically. 我正在尝试以编程方式设置LayoutParams.BELOW Here my code: 这是我的代码:

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;

But it's not being correctly positioned. 但是它的位置不正确。 Any idea on why it is not well positioned? 关于它为什么位置不好的任何想法吗?

The ImageView doesn't have an ID. ImageView没有ID。 You need to give it one. 您需要给它一个。 Either define some constant integer value, or use View.generateViewId() , and call setId() before using it in the layout params: 定义一些常量整数值,或者使用View.generateViewId() ,并在布局参数中使用setId()之前调用setId()

ImageView imageView = new ImageView(this.getActivity());
imageView.setId(View.generateViewId());
...
params.addRule(RelativeLayout.BELOW, imageView.getId());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM