This question already has answers here:
Change position of Google Maps API's "My location" button
(17 answers)
Closed 4 years ago.
I have added a map fragment (API v2) to my app with the map covering the whole screen and a semi-transparent actionbar on top.
The activity uses a theme with android:windowActionBarOverlay set to true.
I have also enabled the "MyLocationButton" on the map, but since the map covers the full height of the screen, the button is covered by the action bar.
How can I make the map fragment draw the location button below the action bar or at the bottom of the screen instead?
Instead of creating your own button, just move the build in button according to the action bar size.
This code works for me and the button is just where the button should be (like in google maps):
// Gets the my location button
View myLocationButton = getSherlockActivity().findViewById(R.id.MainContainer).findViewById(2);
// Checks if we found the my location button
if (myLocationButton != null){
int actionBarHeight = 0;
TypedValue tv = new TypedValue();
// Checks if the os version has actionbar in it or not
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
if (getSherlockActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
// Before the action bar was added to the api
else if(getSherlockActivity().getTheme().resolveAttribute(com.actionbarsherlock.R.attr.actionBarSize, tv, true)){
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
// Sets the margin of the button
ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(myLocationButton.getLayoutParams());
marginParams.setMargins(0, actionBarHeight + 20, 20, 0);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
myLocationButton.setLayoutParams(layoutParams);
}
Just put this code in the onActivityCreated (if you will put it in the onCreateOptionsMenu, it will not support version before 3.0 - because the life cycle there is different.
Another thing, the "R.id.MainContainer" is the container of the map fragment.
I'm using ActionBar Sherlock, but it will work also for regular action bar with a few modifications..
Below (especially in fixMapControlLocations) i've addressed this with ActionBarSherlock.
Issues I had were on narrow screens, and the split action bar having the wrong offset depending on rotation. The isNarrow check through sherlock lets me know if its narrow.
Another key change is i'm setting the padding of the myLocation's parent's parent view. This picks up all controls inside, and based on hierarchyviewer is how google maps is doing it. The Google attribution logo is on the next parent up the tree in a Surface object. Not looking like that is easily movable, so i'm probably just going to end up loosing the bottom action bar's transparency effect to stay in compliance.
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
setUpMapIfNeeded();
getSupportActionBar().setBackgroundDrawable(d);
getSupportActionBar().setSplitBackgroundDrawable(d);
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getExtendedMap();
// Check if we were successful in obtaining the map.
if (map != null) {
setUpMap();
}
}
}
private void setUpMap() {
fixMapControlLocations();
.....
}
private void fixMapControlLocations() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
int actionBarHeight = 0;
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
View myLocationParent = ((View)mapFragment.getView().findViewById(1).getParent());
View myLocationParentParent = ((View)myLocationParent.getParent());
myLocationParentParent.setPadding(0, actionBarHeight, 0, isNarrow()?actionBarHeight:0);
}
public boolean isNarrow() {
return ResourcesCompat.getResources_getBoolean(getApplicationContext(),
R.bool.abs__split_action_bar_is_narrow);
}
You can accomplish this with the recently-added GoogleMap.setPadding() method:
map.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
From the API docs:
This method allows you to define a visible region on the map, to signal to the map that portions of the map around the edges may be obscured, by setting padding on each of the four edges of the map. Map functions will be adapted to the padding. For example, the zoom controls, compass, copyright notices and Google logo will be moved to fit inside the defined region, camera movements will be relative to the center of the visible region, etc.
Also see the description of how padding works in GoogleMap.
This has already been filed as an enhancement (please star it if you haven't already) http://code.google.com/p/gmaps-api-issues/issues/detail?id=4670
As a temporary workaround I have added my own find location button below the actionbar (my map fragment is in a RelativeLayout so I just did alignParentRight and set appropriate margin top).
Then in my onClickHandler I did this:
public void onClickHandler(View target) {
switch (target.getId()) {
case R.id.my_fml_btn:
mMap.setMyLocationEnabled(true);
View fmlBtn = mMapWrapper.findViewById(2); //mMapWrapper is my RelativeLayout
if (fmlBtn != null) fmlBtn.setVisibility(View.INVISIBLE);
break;
}
}
I used hierarchyviewer to find the id of the button that was added by the maps api. It just happens to be the 2nd view added to the map (and set to invisible).
You can of course you can fiddle about with LayoutParams to offset this button rather than hide it but this button only appears after you setMyLocationEnabled to true! (in my use case I prefer to let the user decide before firing up the gps)
Make sure you use ?android:attr/actionBarSize (or ?attr/actionBarSize if you're using ActionBarSherlock) to correctly offset the content of the fragment.
Depending of the effect you're trying to accomplish, either apply this value as margin or padding. I'm guessing that because of the semi-transparant ActionBar, you'll want to try padding, in order to still have the map appear behind it (and keep the see-through effect). I'm just not 100% sure whether padding will actually move the 'Locate me' button down... If not, then probably applying a margin is your only other option.
See here for an example and more details on this attribute.
Related
I have a kotlin app with bottom navigation setup.
I currently have 5 fragments [ProfileFragment, SearchFragment, HomeFragment, SettingsFragment, WebViewFragment]
All of these are just blank fragments. But in my Profile Fragment, I'm showing off a panaroma widget in the top half of the page
I know about making my whole app full screen, but then, on other fragments, content will get hidden under notched displays. And by content, I mean my employer's logo, which he wants, without fail.
So, I tried another way. I made the app full screen and added padding wherever, there was content hiding under the notch. Now, there happen to be various phones, without notches. The content looked unusually padded down, because, well, there was no notch.
If I make adjustments for notched display, the non-notch displays will give issues. And vice-versa.
So, I figured, why not instead of making all activities in my app fullscreen, If I can stretch the ProfileFragment to cover the status bar, or hide the status bar, it'd be a perfect solution.
Is there a way to do either of the following?
Hide the status bar on the ProfileFragment
Stretch the fragment to the top of the screen
Make the fragment full screen, without cutting off the bottom navigation
You can try adding this code in your Activity:
// Hide the status bar.
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
// Remember that you should never show the action bar if the status bar is hidden, so hide that too if necessary.
actionBar?.hide()
More info here: https://developer.android.com/training/system-ui/status#kotlin
AndroidX (support library) has a built-in OnApplyWindowInsetsListener which helps you determine the window insets such as top (status bar) or bottom insets (ie. keyboard) in a device-compatible way.
Since the insets work for API 21+ you have to get the insets manually for below that. Here is an example in Java (v8), hope you get the hang of it:
public class MainActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
View mainContainer = findViewById(R.id.main_container); // You layout hierarchy root
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ViewCompat.setOnApplyWindowInsetsListener(mainContainer , (v, insets) -> {
int statusBarHeight = 0;
if (!isInFullscreenMode(getWindow())) statusBarHeight = insets.getSystemWindowInsetTop();
// Get keyboard height
int bottomInset = insets.getSystemWindowInsetBottom();
// Add status bar and bottom padding to root view
v.setPadding(0, statusBarHeight, 0, bottomInset);
return insets;
});
} else {
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
int statusBarHeight = 0;
if (resourceId > 0 && !isInFullscreenMode(getWindow())) {
statusBarHeight = getResources().getDimensionPixelSize(resourceId);
}
View decorView = getWindow().getDecorView();
decorView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
decorView.getWindowVisibleDisplayFrame(r);
//get screen height and calculate the difference with the useable area from the r
int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
int bottomInset = height - r.bottom;
// if it could be a keyboard add the padding to the view
// if the use-able screen height differs from the total screen height we assume that it shows a keyboard now
//set the padding of the contentView for the keyboard
mainContainer.setPadding(0, statusBarHeight, 0, bottomInset);
});
}
...
}
public static boolean isInFullscreenMode(Window activityWindow) {
return (activityWindow.getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
}
Note that for the bottom inset to work you have to tell Android that your activity is resizable, so in your AndroidManifest.xml:
<application
...>
<activity
android:name=".MainActivity"
...
android:windowSoftInputMode="adjustResize"/>
...
</application>
If you use AppCompatActivity, you can also use:
if(getSupportActionBar() != null) {
getSupportActionBar().hide();
}
in the onCreate methode.
I have been looking for answers on how to place the indeterminate horizontal progress bar below the action bar using AppCompat. I'm able to get the horizontal progress bar to appear, but it is at the top of the action bar. I want it under/below the action bar kind of like how gmail does it (except without the pull to refresh).
I used the following code to have the progress bar appear:
supportRequestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main_activity);
setSupportProgressBarIndeterminate(Boolean.TRUE);
setSupportProgressBarVisibility(true);
but this places the horizontal progress bar at the top of the action bar. Anyone know how to place the progress bar below the action bar?
I faced a similar problem recently and solved it by creating my own progressbar and then aligning it by manipulating getTop() of the content view.
So first create your progressbar.
final LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, 20); //Use dp resources
mLoadingProgressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
mLoadingProgressBar.setIndeterminate(true);
mLoadingProgressBar.setLayoutParams(lp);
Add it to the window (decor view)
final ViewGroup decor = (ViewGroup) getWindow().getDecorView();
decor.addView(mLoadingProgressBar);
And in order to get it to its correct position Im using a ViewTreeObserver that listens until the view has been laid out (aka the View.getTop() isnt 0).
final ViewTreeObserver vto = decor.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
final View content = getView(android.R.id.content);
#Override
public void onGlobalLayout() {
int top = content.getTop();
//Dont do anything until getTop has a value above 0.
if (top == 0)
return;
//I use ActionBar Overlay in some Activities,
//in those cases it's size has to be accounted for
//Otherwise the progressbar will show up at the top of it
//rather than under.
if (getSherlock().hasFeature((int) Window.FEATURE_ACTION_BAR_OVERLAY)) {
top += getSupportActionBar().getHeight();
}
//Remove the listener, we dont need it anymore.
Utils.removeOnGlobalLayoutListener(decor, this);
//View.setY() if you're using API 11+,
//I use NineOldAndroids to support older
ViewHelper.setY(mLoadingProgressBar, top);
}
});
Hope that makes sense for you. Good luck!
I am writing an application in android using Google map-V2 API. I want to over lay action bar just as in the Google map application. And I enabled "My Location " button. The problem now is that my location button is under the action bar. Is there any way to re-position this button. I want to make an app some what similar to Maps. I am new to android so please help.
You can set padding to the map.
This solved the problem - overlays over the map on the top (I used 48 dips, but you can overlay action bar and then get actual height of it (?android:attr/actionBarSize))
mapFragment.getMap().setPadding(0, dpToPx(48), 0, 0);
(DP to PX function is from this SO answer)
You can reposition your location button easily
View plusMinusButton = suppormanagerObj.getView().findViewById(1);
View locationButton = suppormanagerObj.getView().findViewById(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);
you can also set padding after setting alignment of the location button
mMap.setPadding(0, 0, 30, 105);
You can not alter the MyLocationButton in any way, but enable and disable it. There is already a request for this.
Feel free to disable the button and just implement your own one.
You would have something like this:
mMap.getUiSettings().setMyLocationButtonEnabled(false);
I solved this problem in my map fragment by re positioning my location button to the right bottom corner of view using code below,
here is my Maps Activity.java :-
add this lines of code in onCreate() method,
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapView = mapFragment.getView();
mapFragment.getMapAsync(this);
and here is onMapReady() code :-
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
if (mapView != null &&
mapView.findViewById(Integer.parseInt("1")) != null) {
// Get the button view
View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
// and next place it, on bottom right (as Google Maps app)
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
// position on right bottom
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 30, 30);
}
}
I hope, this will solve your problem. Thanks.
Instead of the findViewById solutions, I used the findViewWithTag to get a reference to the button. Using a string seemed more readable and reliable to me.
View myLocationButton = mMap.findViewWithTag("GoogleMapMyLocationButton");
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) myLocationButton.getLayoutParams();
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
Just use GoogleMap.setPadding(left, top, right, bottom), which allows you to indicate parts of the map that may be obscured by other views. Setting padding re-positions the standard map controls, and camera updates will use the padded region.
https://developers.google.com/maps/documentation/android/map#map_padding
How can i customize the position of the builtin zoom controls in a GoogleMap V2 ?
There are a lot of questions related to this topic for the Version 1 of Google Maps library.
Placing Zoom Controls in a MapView
How to reposition built-in zoom controls in MapView?
How to layout zoom Control with setBuiltInZoomControls(true)?
However, i wasn't able to find any questions in relation to the V2 of the library.
In the V2, there's no method
(LinearLayout) mapView.getZoomControls();
all the previously mentioned questions becomes obsolete.
Thanks in advance
Depending on what you're trying to do, you might find GoogleMap.setPadding() useful (added in September 2013).
map.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
From the API docs:
This method allows you to define a visible region on the map, to signal to the map that portions of the map around the edges may be obscured, by setting padding on each of the four edges of the map. Map functions will be adapted to the padding. For example, the zoom controls, compass, copyright notices and Google logo will be moved to fit inside the defined region, camera movements will be relative to the center of the visible region, etc.
Also see the description of how padding works in GoogleMap.
Yes, you can change position of ZoomControl and MyLocation button with small hack.
In my sample I have SupportMapFragment, which is inflated from xml layout.
View ids for ZoomControl and MyLocation button:
ZoomControl id = 0x1
MyLocation button id = 0x2
Code to update ZoomControl position:
// Find map fragment
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
// Find ZoomControl view
View zoomControls = mapFragment.getView().findViewById(0x1);
if (zoomControls != null && zoomControls.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
// ZoomControl is inside of RelativeLayout
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) zoomControls.getLayoutParams();
// Align it to - parent top|left
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
// Update margins, set to 10dp
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
getResources().getDisplayMetrics());
params.setMargins(margin, margin, margin, margin);
}
I use MapFragment not SupportMapFragment:
import android.util.TypedValue;
in onCreate
// Find map fragment
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapview);
int ZoomControl_id = 0x1;
int MyLocation_button_id = 0x2;
// Find ZoomControl view
View zoomControls = mapFragment.getView().findViewById(ZoomControl_id);
if (zoomControls != null && zoomControls.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
// ZoomControl is inside of RelativeLayout
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) zoomControls.getLayoutParams();
// Align it to - parent top|left
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
// Update margins, set to 10dp
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
getResources().getDisplayMetrics());
params.setMargins(margin, margin, margin, margin);
}
Just for the record:
Navigation-controls are 0x4
So in total:
#LayoutRes final int ZOOM_CONTROL_ID = 0x1;
#LayoutRes final int MY_LOCATION_CONTROL_ID = 0x2;
#LayoutRes final int NAVIGATION_CONTROL_ID = 0x4;
I am using this example: https://github.com/galex/android-mapviewballoons
My problem is that the clickable area is wider than the marker itself. For example, my Google Map marker is 25x25 then the clickable area would extend up to 70x70. This is a big problem for overlapping markers.
When I clicked on the tip of that arrow, onTap is activated, even though the tap area is far from the marker.
Please help me. Thanks.
This is the default behaivior of ItemizedOverlay. 25x25 px is generally not an adquate touchable area for most human fingers.
You should override the hitTest() method if you want to modify the way an overlay item hit is tested.
For debugging :
Try using a TouchDelegate for the View, you can specify the Touch rect for a give View
An example showing how to use the TouchDelegate :
public class TouchDelegateSample extends Activity {
Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.touch_delegate_view);
mButton = (Button)findViewById(R.id.delegated_button);
View parent = findViewById(R.id.touch_delegate_root);
// post a runnable to the parent view's message queue so its run
after
// the view is drawn
parent.post(new Runnable() {
#Override
public void run() {
Rect delegateArea = new Rect();
Button delegate = TouchDelegateSample.this.mButton;
delegate.getHitRect(delegateArea);
delegateArea.top -= 200;
TouchDelegate expandedArea = new TouchDelegate(delegateArea,
delegate);
// give the delegate to an ancestor of the view we're
delegating the
// area to
if (View.class.isInstance(delegate.getParent())) {
((View)delegate.getParent()).setTouchDelegate(expandedArea);
}
}
});
}
}
hitTest()
See if a given hit point is within the bounds of an item's marker. Override to modify the way an item is hit tested. The hit point is relative to the marker's bounds. The default implementation just checks to see if the hit point is within the touchable bounds of the marker.