我需要创建一个简单的应用程序,其中包含 1. 可以显示当前位置 (LocationListener?)、两个标记等的自定义 MapFragment。 2. 简单的空片段。
应用程序不得使用支持 v4 (sdk 11+) / FragmentActivity。
空片段。
XML:
<?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="@android:color/black" >
</RelativeLayout>
班级:
public class FirstFragment extends Fragment{
public FirstFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_fragment, container, false);
return view;
}
}
地图片段(尝试使其成为单例)。
XML:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment"/>
班级
public class ThirdMapFragment extends MapFragment {
public static MapFragment instance;
@Override
public View onCreateView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) {
View view;
view = arg0.inflate(R.layout.map_fragment, arg1, false);
return view;
}
public static MapFragment getInstance() {
if (instance == null) {
instance = newInstance();
}
// NullPointerException in getMap() ???
// instance.getMap().addMarker(new MarkerOptions().position(new LatLng(41.1, 39)));
return instance;
}
@Override
public void onCreate(Bundle arg0) {
super.onCreate(arg0);
}
}
主要活动:
public class ActivityMain extends Activity implements OnClickListener {
FragmentManager fragmentManager;
FragmentTransaction transaction;
FirstFragment firstFragment;
MapFragment mapFragment;
// Buttons
Button b4;
int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fragmentManager = getFragmentManager();
transaction = fragmentManager.beginTransaction();
b4 = (Button) findViewById(R.id.button4);
b1.setOnClickListener(this);
firstFragment = new FirstFragment();
mapFragment = ThirdMapFragment.getInstance();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
makeTransaction(v.getId());
}
private void makeTransaction(int id) {
i++;
transaction = fragmentManager.beginTransaction();
if (i == 1) {
transaction.replace(R.id.relativeLayout, firstFragment).commit();
} else if (i == 2) {
transaction.replace(R.id.relativeLayout, secondFragment).commit();
} else {
transaction.replace(R.id.relativeLayout, mapFragment).commit();
i = 0;
}
}
}
R.id.relativeLayout - main.xml 中的布局
但我没有看到地图(带有缩放按钮的空白屏幕)以及如何制作 LocationListener?谢谢。