[英]OnClick event of button not working always
fragment_maps.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.MapsFragment">
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="@+id/hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:focusable="true"
android:text="Pickup Location">
</Button>
</FrameLayout>
MapsFragment.java
我认为由于 SupportMapFragment 或 Framelayout 的 xml 实现不当,有时单击按钮工作有时不工作
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_maps, container,false);
button = (Button) view.findViewById(R.id.hello);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),"Clicked",Toast.LENGTH_SHORT).show();
}
});
location_permissions = new location_permissions(getContext());
locationCallback = new LocationCallback();
locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(getContext());
locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
SettingsClient client = LocationServices.getSettingsClient(getContext());
mtask = client.checkLocationSettings(builder.build());
supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
requestpermission();
// google maps
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
// request GPS turn on if Gps is off
requestGPSCheck();
// gets device current location & animate to current Latlong
callback();
}
});
return view;
}
我在 Button OnClick 事件上设置了 Toast 消息,它总是不工作可能是由于焦点?
而不是使用
Toast.makeText(getContext(),"Clicked",Toast.LENGTH_SHORT).show();
尝试使用
Toast.makeText(getActivity().getApplicationContext(),"Clicked",Toast.LENGTH_SHORT).show();
getContext()使用当前视图作为上下文,因此如果尚未加载地图,则可能会导致上下文尚不可用。 getApplicationContext()使用应用程序的上下文,该上下文在加载此片段时已经可用。
试着让我知道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.