首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android RelativeLayout以编程方式设置"centerInParent“

Android RelativeLayout以编程方式设置"centerInParent“
EN

Stack Overflow用户
提问于 2010-10-21 16:59:21
回答 2查看 131.6K关注 0票数 143

我有一个这样的RelativeLayout:

代码语言:javascript
复制
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dip">

    <Button
        android:id="@+id/negativeButton"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:textSize="20dip"
        android:textColor="#ffffff"
        android:layout_alignParentLeft="true"
        android:background="@drawable/black_menu_button"
        android:layout_marginLeft="5dip"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/> 

    <Button
        android:id="@+id/positiveButton"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:textSize="20dip"
        android:textColor="#ffffff"
        android:layout_alignParentRight="true"
        android:background="@drawable/blue_menu_button"
        android:layout_marginRight="5dip"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

我希望能够以编程方式为positiveButton设置与以下内容相同的效果:

代码语言:javascript
复制
android:layout_centerInParent="true"

我怎样才能通过编程实现这一点呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-10-21 17:13:12

完全未经测试,但这应该可以工作:

代码语言:javascript
复制
View positiveButton = findViewById(R.id.positiveButton);
RelativeLayout.LayoutParams layoutParams = 
    (RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
positiveButton.setLayoutParams(layoutParams);

在清单中的活动中添加android:configChanges="orientation|screenSize"

票数 417
EN

Stack Overflow用户

发布于 2015-03-26 01:24:19

为了从鲁本响应中添加另一种风格,我像这样使用它来根据条件添加或删除此规则:

代码语言:javascript
复制
    RelativeLayout.LayoutParams layoutParams =
            (RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();

    if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
        // if true center text:
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        holder.txtGuestName.setLayoutParams(layoutParams);
    } else {
        // if false remove center:
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
        holder.txtGuestName.setLayoutParams(layoutParams);
    }
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3985787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档