目前我正在制作地图,我需要在片段上执行按钮的onclicklistner事件,该片段在运行时会膨胀。手段按钮已存在于当前活动中,通过此按钮,我需要在运行时添加的片段上使用onclicklistner
。
这是我的代码:
Map.java:我在其中添加片段。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
Frontpage fragment6 = new Frontpage();
fragmentTransaction.replace(R.id.frame_container, fragment6);
fragmentTransaction.commit();
}
这是frontpage.java类。我在map.java中将此类添加为片段。
package com.example.vroomroutess;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.example.vroomroutess.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class Frontpage extends Fragment {
SharedPreferences file;
DatabaseHandler db;
private GoogleMap googleMap;
ArrayList<LatLng> markerPoints;
float[] results = new float[100];
List<Double> list;
List<Double> list1;
int i;
public Frontpage() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.mapfragment, container,false);
file = getActivity().getSharedPreferences("Ryans_play", getActivity().MODE_WORLD_WRITEABLE);
PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
ViewConfiguration config = ViewConfiguration.get(getActivity());
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception ex) {
// Ignore
}
db = new DatabaseHandler(getActivity());
//ActionBar actionBar=getActionBar();
/** Simply to show the maps */
LocationManager service = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
final Location location = service.getLastKnownLocation(provider);
// LatLng userLocation = new
// LatLng(location.getLatitude(),location.getLongitude());
googleMap = ((SupportMapFragment) getActivity().getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//LatLng ltlng = new LatLng(lati, lngi);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.getUiSettings().setTiltGesturesEnabled(true);
getCurrentLocation();
markerPoints = new ArrayList<LatLng>();
googleMap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
// Already 10 locations with 8 waypoints and 1 start location
// and 1 end location.
// Upto 8 waypoints are allowed in a query for non-business
// users
if (markerPoints.size() >= 10) {
return;
}
// Adding new item to the ArrayList
markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and for
* the end location, the color of marker is RED and for the rest
* of markers, the color is AZURE
*/
if (markerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (markerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
} else {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
}
// Add new marker to the Google Map Android API V2
googleMap.addMarker(options);
}
});
return rootView;
}
void getCurrentLocation() {
Location myLocation = googleMap.getMyLocation();
if (myLocation != null) {
double dLatitude = myLocation.getLatitude();
double dLongitude = myLocation.getLongitude();
googleMap.addMarker(new MarkerOptions().anchor(0.0f, 1.0f)
.position(new LatLng(dLatitude, dLongitude))
.title("My Location"));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
dLatitude, dLongitude), 16));
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(new CameraPosition.Builder()
.target(new LatLng(dLatitude, dLongitude)).zoom(15.5f).bearing(0)
.tilt(25).build()
), new GoogleMap.CancelableCallback() {
@Override
public void onFinish() {
// Your code here to do something after the Map is rendered
// Toast.makeText(getApplicationContext(),
// ""+location.getLatitude() , Toast.LENGTH_LONG).show();
}
@Override
public void onCancel() {
// Your code here to do something after the Map rendering is
// cancelled
}
});
Log.i("Move camrasj4444444444444444444", "mmmmmmmmmmmmmmmmmmmmmmmm");
} else {
Toast.makeText(getActivity(), "Unable to fetch the current location",
Toast.LENGTH_SHORT);
}
}
}
我需要在map.java中执行这样的onclick事件:
drawmap = (Button)findViewById(R.id.mapbutton);
drawmap.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
googleMap.clear();
if (markerPoints.size() < 0) {
Toast.makeText(getApplicationContext(),
"You don't selected any ponit", Toast.LENGTH_LONG)
.show();
} else {
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
list = new ArrayList<Double>();
list1 = new ArrayList<Double>();
PolylineOptions po = new PolylineOptions().geodesic(true);
po.width(5);
po.color(Color.RED);
for (i = 0; i < markerPoints.size(); i++) {
LatLng ltlng1 = markerPoints.get(i);
System.out.println("value of i----" + i);
list.add(markerPoints.get(i).latitude);
list1.add(markerPoints.get(i).longitude);
options.position(ltlng1);
if (i == 0) {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (markerPoints.size() - 1 == i) {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
} else {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
}
// Add new marker to the Google Map Android API V2
googleMap.addMarker(options);
po.add(ltlng1);
}
googleMap.addPolyline(po);
System.out.println("list size----------" + list.size());
for (int j = 0; j < list.size() - 1; j++) {
int a;
if (j == list.size()) {
a = j - 1;
} else {
a = j + 1;
}
System.out.println("Value of a==" + a + "Value of j=="
+ j);
Location.distanceBetween(list.get(j), list1.get(j),
list.get(a), list1.get(a), results);
Toast.makeText(getApplicationContext(),
"distance ====" + results[j], Toast.LENGTH_LONG)
.show();
}
}
}
});
但是这给了我错误。我的logcat:
05-06 14:25:04.825: E/AndroidRuntime(2200): FATAL EXCEPTION: main
05-06 14:25:04.825: E/AndroidRuntime(2200): Process: com.example.vroomroutess, PID: 2200
05-06 14:25:04.825: E/AndroidRuntime(2200): java.lang.NullPointerException
05-06 14:25:04.825: E/AndroidRuntime(2200): at com.example.vroomroutess.Map$4.onClick(Map.java:186)
05-06 14:25:04.825: E/AndroidRuntime(2200): at android.view.View.performClick(View.java:4438)
05-06 14:25:04.825: E/AndroidRuntime(2200): at android.view.View$PerformClick.run(View.java:18422)
05-06 14:25:04.825: E/AndroidRuntime(2200): at android.os.Handler.handleCallback(Handler.java:733)
05-06 14:25:04.825: E/AndroidRuntime(2200): at android.os.Handler.dispatchMessage(Handler.java:95)
05-06 14:25:04.825: E/AndroidRuntime(2200): at android.os.Looper.loop(Looper.java:136)
05-06 14:25:04.825: E/AndroidRuntime(2200): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-06 14:25:04.825: E/AndroidRuntime(2200): at java.lang.reflect.Method.invokeNative(Native Method)
05-06 14:25:04.825: E/AndroidRuntime(2200): at java.lang.reflect.Method.invoke(Method.java:515)
05-06 14:25:04.825: E/AndroidRuntime(2200): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-06 14:25:04.825: E/AndroidRuntime(2200): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-06 14:25:04.825: E/AndroidRuntime(2200): at dalvik.system.NativeStart.main(Native Method)
05-06 14:25:04.825: W/dalvikvm(2200): threadid=1: thread exiting with uncaught exception (group=0xb2cbeb20)
如何在当前活动中获取添加的片段对象?片段成功添加。错误提供nullpointerexeception
。并且它在googlemap.clear();
map.java
处给我一个错误意味着我无法在运行时添加Map.java
的片段中获取地图。那么我该如何解决这个问题呢?谢谢你的帮助。