我正在尝试使用此处建议的解决方案移动 Google Maps v2 中的“我的位置”按钮。
我遇到的问题是我得到了一个 nullpointerexception,结果this.getView()
返回 null,这很奇怪,因为当到达那条线时,已经创建了片段。onCreateView() 例程已经完成,对地图进行了一些初始化,所以我确定它存在。应用程序的其余部分也可以很好地访问此地图对象。
我的 main.xml 文件的相关部分(当然,这个 RelativeLayout 中还有很多,但这是唯一存在的地图片段):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.squirrel.hkairpollution.MySupportMapFragment"
/>
和代码:
package com.squirrel.hkairpollution;
(imports omitted)
public class MySupportMapFragment extends SupportMapFragment {
private static final String TAG = HKAirPollution.TAG;
public MySupportMapFragment() {
return;
}
@Override
public View onCreateView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) {
Log.v(TAG, "In overridden onCreateView.");
View v = super.onCreateView(arg0, arg1, arg2);
Log.v(TAG, "Initialising map.");
initMap();
Log.v(TAG, "Moving the MyPositionButton");
resetMyPositionButton();
return v;
}
private void initMap(){
UiSettings settings = getMap().getUiSettings();
settings.setAllGesturesEnabled(true);
settings.setMyLocationButtonEnabled(true);
LatLng latLong = new LatLng(22.320542, 114.185715);
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(latLong,11));
}
/**
* Move my position button at the bottom of map
*/
private void resetMyPositionButton()
{
//deep paths for map controls
ViewGroup v1 = (ViewGroup)this.getView();
ViewGroup v2 = (ViewGroup)v1.getChildAt(0);
ViewGroup v3 = (ViewGroup)v2.getChildAt(0);
ViewGroup v4 = (ViewGroup)v3.getChildAt(1);
//my position button
View position = (View)v4.getChildAt(0);
int positionWidth = position.getLayoutParams().width;
int positionHeight = position.getLayoutParams().height;
//lay out position button
RelativeLayout.LayoutParams positionParams = new RelativeLayout.LayoutParams(positionWidth,positionHeight);
int margin = positionWidth/5;
positionParams.setMargins(0, 0, 0, margin);
positionParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
positionParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
position.setLayoutParams(positionParams);
}
}