如何在不在xml中的代码中设置RelativeLayout布局参数?

Qin*_*ing 111 android android-layout android-relativelayout

例如,我想在屏幕上添加3个按钮:一个对齐左边,一个对齐中心,最后一个对齐右边.

如何在代码中设置其布局,而不是xml

Cri*_*ian 266

只是一个基本的例子:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
Button button1;
button1.setLayoutParams(params);

params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
Button button2;
button2.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)

如您所见,这是您必须做的:

  1. 创建一个RelativeLayout.LayoutParams对象.
  2. 使用addRule(int)addRule(int, int)设置规则.第一种方法用于添加不需要值的规则.
  3. 将参数设置为视图(在本例中为每个按钮).

  • 这里有几个问题.首先,我没有看到你实际上在哪里实例化button1或button2.其次,动态声明的视图(ImageViews,Buttons等)实例化为id为-1.id为-1将不适用于规则. (15认同)
  • 没有像LayoutParams这样的东西.基类实际上是`ViewGroup.LayoutParams`.如果你想缩短它,只需添加一个包含`RelativeLayout.LayoutParams`的导入. (3认同)

Ami*_*per 17

    RelativeLayout layout = new RelativeLayout(this);
    RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    layout.setLayoutParams(labelLayoutParams);


   // If you want to add some controls in this Relative Layout
    labelLayoutParams = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    labelLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);


    ImageView mImage = new ImageView(this);
    mImage.setBackgroundResource(R.drawable.popupnew_bg);        
    layout.addView(mImage,labelLayoutParams);

    setContentView(layout);
Run Code Online (Sandbox Code Playgroud)


Roh*_*wal 6

像这样的东西......

 RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.widget43);
                // ListView listView = (ListView) findViewById(R.id.ListView01);

                LayoutInflater inflater = (LayoutInflater) this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                // View footer = inflater.inflate(R.layout.footer, null);
                View footer = LayoutInflater.from(this).inflate(R.layout.footer,
                        null);
                final RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.FILL_PARENT,
                        RelativeLayout.LayoutParams.FILL_PARENT);
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1);
footer.setLayoutParams(layoutParams);
Run Code Online (Sandbox Code Playgroud)