Android 以编程方式定位按钮
嗨,我的布局是这样的:Android 以编程方式定位按钮,android,android-relativelayout,Android,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"
<?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));
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
addContentView(startButton, lp);
我希望这会有所帮助。为您的相对视图提供一个id
,如下所示,以便稍后在此布局中添加新视图
<?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 >
谢谢,我在类型ViewGroup的addRule:Undefined上遇到一个错误。LayoutParams@HS+1为您的精彩答案加油!
<?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 >
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);