以编程方式定位Android按钮

时间:2014-03-09 14:20:59

标签: android relativelayout

嗨,我的布局是这样的:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/BlanchedAlmond" >

<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.MapFragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</RelativeLayout >

我以编程方式添加如下按钮:

    ImageButton startButton = new ImageButton(this);
    startButton.setBackground(getResources().getDrawable(R.drawable.startbutton));

    addContentView(startButton, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

任何人都可以指导我如何将按钮放在底部并居中。我见过其他类似的问题,但我无法实现我的目标。

2 个答案:

答案 0 :(得分:2)

如下所示向id提供RelativeLayout,以便稍后向此布局添加新视图...

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/BlanchedAlmond" >

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout >

现在,创建ImageButton并添加到活动布局,如下所示......

RelativeLayout rootLayout = (RelativeLayout) findViewById(R.id.layout);

ImageButton startButton = new ImageButton(this);
startButton.setImageResource(R.drawable.ic_launcher);

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);

rootLayout.addView(startButton, lp);

答案 1 :(得分:1)

您只需将rules封装的verbs添加到LayoutParams

即可

例如

ImageButton startButton = new ImageButton(this);
startButton.setBackground(getResources().getDrawable(R.drawable.startbutton));

LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);

addContentView(startButton, lp);

我希望这会有所帮助。