我有一个包含谷歌地图的片段:
<com.google.android.gms.maps.MapView
android:id="@+id/mapview"
android:layout_width="match_parent"
android:layout_height="match_parent"
map:cameraZoom="13"
map:mapType="normal"
map:uiZoomControls="false"
map:uiRotateGestures="true"
map:uiScrollGestures="true"
map:uiZoomGestures="true"
map:uiTiltGestures="false" />
地图占据了整个屏幕并启用了mylocation:
map.setMyLocationEnabled(true);
下面的代码应该将mylocation按钮对齐到屏幕的左上角:
// Get the mylocation button view
View locationButton = ((View) mapview.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
然而,-这只会将按钮对齐到屏幕的顶部中心。但是,如果我加上:
if (Build.VERSION.SDK_INT >= 17) {
rlp.addRule(RelativeLayout.ALIGN_PARENT_START);
}
则正确地向左对齐。问题是ALIGN_PARENT_START不能在api 17之前以编程方式使用,我需要从较低的api级别进行支持。为什么不align_parent_left工作在它自己的向左对齐按钮?
这是我移动my location按钮的实现:
<LinearLayout
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
android:name="com.google.android.gms.maps.SupportMapFragment">
</fragment>
.
.
.
On my activity:
mapFragment = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.myMap));
//if you're using a fragment use:
//mapFragment = ((SupportMapFragment) getChildFragmentManager() .findFragmentById(R.id.myMap));
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
//add map adjustments here//
//then this is where you move the my location button
View locationButton = ((View) mapFragment.getView().findViewById(Integer.parseInt("1")).
getParent()).findViewById(Integer.parseInt("2"));
// and next place it, for exemple, on bottom right (as Google Maps app)
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
// position on right bottom
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
rlp.setMargins(0, 0, 30, 30);
}
});
不幸的是,有一种方法是从头创建
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams((int)(45*density),(int)(45*density));
rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
rlp.setMargins((int)(5*density), 0, 0, (int)(5*density));
locationButton.setLayoutParams(rlp);
其中密度为,例如
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
dispWidth = metrics.widthPixels;
dispHeight = metrics.heightPixels;
density = metrics.scaledDensity;