How can I style Android tabs to get 3d look? - android

I want to create an Android tab view to look like this image:
I guess there are many ways to Rome, but I think I still haven't found the ideal one. My idea was to cut out a divider and an active divider and place them between the buttons. However, I don't know if this would be such a good solution because I still would need different styling for the first and last button. I already have a 9 patch for the surrounding (grey) container.
I've also thought about making a red 9 patch for the red bar, and than just style the selected button. The problem with this solution is that I'd still have to place the top diagonal white lines according to the number of buttons.
Does anyone have a better solution for me?

Here's another approach: to separate the header from the tabs. A bit complicated, yes, but the benefits are:
It allows you to define common tabs style;
Supports any number of buttons.
On this picture the buttons are of different width, so in reality an additional ImageView may be needed to the left of the header.
Let's create our header view as a LinearLayout. We can put upper dividers and stretchable gaps with the same layout_weight.
public class HeaderLayout extends LinearLayout {
public HeaderLayout(Context context) {
super(context);
initView();
}
public HeaderLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public void setNumberOfColumns(int number) {
removeAllViews();
for (int i = 0; i < number; i++) {
addView(getColumnView(), getColumnLayoutParams());
// We don't need a divider after the last item
if (i < number - 1) {
addView(getDividerView(), getDividerLayoutParams());
}
}
}
private void initView() {
setBackgroundResource(R.drawable.header_bg);
}
private View getColumnView() {
return new View(getContext());
}
private View getDividerView() {
ImageView dividerView = new ImageView(getContext());
dividerView.setImageResource(R.drawable.header_divider);
dividerView.setScaleType(ImageView.ScaleType.FIT_XY);
return dividerView;
}
private LayoutParams getColumnLayoutParams() {
return new LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f);
}
private LayoutParams getDividerLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
}
}
Where R.drawable.header_bg is a 9patch:
And R.drawable.header_divider is a simple (optionally transparent) bitmap:
For me personally, making different background for the first and the last button is the least difficult solution, but it depends on the actual task.

Related

Custom ImageButton, which method to override for simplest RadioButton interface?

I am in the process of making a custom view that is essentially an ImageButton with added logic so it also have the behavior of a RadioButton. All I want to do is have it built into the view that when the user clicks the button the image is changed, an internal boolean is marked true to note it is selected, and an interface method is called to let the RadioGroup it is a part of to unselect all the other views within it. I don't want to impact the existing behavior of the base ImageButton whatsoever.
I've only made one other custom view before and that was by following a tutorial almost exactly to the letter and since there are so many different methods inhereted from View that deal with clicks/touches (i.e. onTouch, onClick, motion event, etc.) taking it all in has left me a bit confused. I am fine writing the interface itself, its the modification of ImageButton where I'm not too sure how to attack it.
So, I ask you all: What method/methods do I need to override to add this simple functionality, while not impacting the current behavior of ImageButton, nor screwing up the ability to set an onTouchListener for the button that will perform additional actions on click without compromising this built in radio button logic? If I need to override something that will mess with the default behavior I mentioned, what do I need to put in the new method to restore that functionality?
This is what I have so far:
public class RadioImageButton extends AppCompatImageButton implements RadioCheckable {
//Default constructor
public RadioImageButton(Context context) {
super(context);
initView();
}
//Constructor with defined attributes
public RadioImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
parseAttributes();
initView();
}
//Constructor with defined attributes and attributes taken from style defaults that aren't defined
public RadioImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
//=========================================================================
// Setup
//=========================================================================
private void initView()
{
}
private void parseAttributes()
{
}
}
The approach I would like to take would be something like:
...All other code I already showed
mChecked = false;
#Overide
void onClick(...)
{
mChecked = true;
setImageSource(R.example.checked_image); // Or I can use a selector resource
*Call to Radio Interface*;
mOnTouchListener.onTouch(v, event); //Handle user onTouchListener
}
...
and leave all the other code alone, though I'm sure it isn't quite that simple.
I thought a good start would be trying to find the source code for the default ImageButton class and set mine up to be a near replica so I can understand how it works and then modify from there, but all I could really find was this:
https://android.googlesource.com/platform/frameworks/base/+/android-7.0.0_r35/core/java/android/widget/ImageButton.java
and there is no way that is the actual source because pressing Ctrl+O shows many more functions that ImageButton defines that are not inherited from another class; regardless, that link is not at all helpful as its basically a giant comment with little to no code.
Thanks for any suggestions that will help me accomplish this in the most straightforward way.
EDIT: #pskink - Looking through the code you provided, it seems like it is trying to generate a matrix in order to transform the provided drawable (src) so that it fits into a new rectangle (dst) while maintaining the aspect ratio and positioning (hence ScaleToFit.CENTER). I would assume the destination rectangle would be the bounds of the view the drawable is contained in, which in this case is the RadioButton, but while stepping through the override of the "draw()" method it doesn't quite seem to be doing that, though I'm not quite sure how cavas.concat(matrix) is resolved so I'm not positive. Regardless it doesn't seem to work as intended or I am somehow using it wrong.
While maybe not the most robust method, it seems like the most straightforward, yet effective way to handle what I wanted to do was to leverage the Matrix class and its powerful scaling/transformation tools, specifically "setRectToRect()". Creating a custom view that extends RadioButton instead of ImageButton allowed me to make use of the existing RadioGroup, while manipulating characteristics of the button's drawables in the new classes Constructor achieved the behavior I was looking for.
Custom RadioButton class:
public class RadioImageButton extends android.support.v7.widget.AppCompatRadioButton {
int stateDrawable; //Resource ID for RadioButton selector Drawable
D scaledDrawable; //Post-scaling drawable
public RadioImageButtonTwo(Context context) {
super(context);
initView();
}
public RadioImageButtonTwo(Context context, AttributeSet attrs) {
super(context, attrs);
parseAttributes(attrs);
initView();
}
private void parseAttributes(AttributeSet attrs)
{
TypedArray styledAttrs = getContext().obtainStyledAttributes(attrs,R.styleable.RadioImageButtonTwo);
try {
// Obtain selector drawable from attributes
stateDrawable = styledAttrs.getResourceId(R.styleable.RadioImageButtonTwo_button_sDrawable, R.drawable.test_draw2);
} finally {
styledAttrs.recycle(); //Required for public shared view
}
}
private void initView()
{
scaledDrawable = new D(getResources(),stateDrawable); // Create scaled drawable
setBackground(scaledDrawable); // Apply scaled drawable
setButtonDrawable(android.R.color.transparent); // "Disable" button graphic
}
}
See more on setting up a custom view here: https://developer.android.com/training/custom-views/create-view#customattr
Custom drawable class "D" that includes fitCenter scaling thanks to #pskink:
class D extends StateListDrawable {
private Rect bounds = new Rect();
private RectF src = new RectF();
private RectF dst = new RectF();
private Matrix matrix = new Matrix();
public D(Resources r, int resId) {
try {
XmlResourceParser parser = r.getXml(resId);
int type;
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
if (type == XmlPullParser.START_TAG && parser.getName().equals("selector")) {
inflate(r, parser, Xml.asAttributeSet(parser));
break;
}
}
} catch (XmlPullParserException | IOException e) {
e.printStackTrace();
}
}
#Override
public void draw(Canvas canvas) {
Drawable current = getCurrent();
bounds.set(0, 0, current.getIntrinsicWidth(), current.getIntrinsicHeight());
current.setBounds(bounds);
src.set(bounds);
dst.set(getBounds());
matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
canvas.concat(matrix);
super.draw(canvas);
}
}
Note that for whatever reason setting the button drawable itself to this custom drawable breaks the scaling, so changing the background to the custom drawable and setting the button drawable to transparent was the only way this worked. This custom drawable could easily be expanded upon to have more scaling type options and another view attribute could be defined to allow the user to choose the scaling type through XML.
This custom ImageView that mimics the (pointed out by pskink aswell) could also prove helpful in this task, as it too utilizes the Matrix class to implement multiple types of image scaling: https://github.com/yqritc/Android-ScalableImageView

Programmatically change one attribute on custom style

I am creating several textviews that all use the same style. I am attempting to use a SeekBar to update the textsize within the Style so it applies to all textviews with a minimal amount of code. I know I can use a SeekBar to set the textsize of the textviews individually but that seems like a lot of work. The problem is that everywhere I look all I find is that you cannot change the style. Is there any other work around besides doing code like below:
Define my textviews
TextView tv1 = (TextView)findViewById(R.id.tv1);
TextView tv2 = (TextView)findViewById(R.id.tv2);
TextView tv3 = (TextView)findViewById(R.id.tv3);
Inside my SeekBar
progress = seekBarProgress;
if(progress == 0)
{
tv1.setTextSize(12);
tv2.setTextSize(12);
tv3.setTextSize(12);
}
if(progress == 1)
{
tv1.setTextSize(14);
tv2.setTextSize(14);
tv3.setTextSize(14);
}
Etc etc..
I would like to be able to change one attribute of a custom style. I cannot change it all together to a different custom style because I am going to do SeekBars for Text size, text color, background color, etc. If I did custom styles for each one there would be TONS.
Since I will have a lot of textviews doing this method seems illogical. Is there a better way? Thanks.
GOT THE ANSWER!
Instead of changing the style I retrieve the child and then the child of that child and change it accordingly like below.
LinearLayout masterLayout = (LinearLayout)findViewById(R.id.masterLayout);
int childCount = masterLayout.getChildCount();
for(int i = 0; i < childCount; i++)
{
LinearLayout innerChild = ((LinearLayout)masterLayout.getChildAt(i));
int childOfChildCount = innerChild.getChildCount();
for(int x = 0; x < childOfChildCount; x++)
{
((TextView)innerChild.getChildAt(x)).setTextSize(30);
}
}
What about group these TextView in only one Layout? Then change it programmatically.
In my example I group all of TextViews in only one LinearLayout.
LinearLayout ll = (LinearLayout) findViewById(R.id.layout);
int childCount = ll.getChildCount();
for (int i=0; i<childCount; i++){
((TextView)ll.getChildAt(i)).setTextSize(20);
}
Be sure that you only have TextViews in your layout.
I know that you have already implemented and accepted a solution, however, I have been thinking about this for a while for myself, and have come up with an alternative, more generic solution which may be of use. This involves four elements
Creating an interface for the style changed events
Creating a handler for the style changed events
Extending TextView to have one or more style changed events
Triggering the style change events
Although this is more code it has the advantages of being independent of layouts, and of the view classes (ie the same handler can be used for different View Classes if you also wanted to change the font size of Buttons, EditTexts etc).
The example below just implements a text size change, but the same technique could be used to implement any other style changes.
The Interface
public interface StyleChange {
void onTextSizeChanged(float size);
}
The Handler
public class TextStyleHandler {
private static TextStyleHandler instance;
private LinkedList<StyleChange> listeners = new LinkedList<>();
public static TextStyleHandler getInstance() {
if (instance == null) instance = new TextStyleHandler();
return instance;
}
public void register(StyleChange item) {
listeners.add(item);
}
public void unregister(StyleChange item) {
listeners.remove(item);
}
public void setTextSize(float f) {
for (StyleChange listener:listeners)
listener.onTextSizeChanged(f);
}
}
The Extended TextView
public class StyledTextView extends TextView implements StyleChange {
public StyledTextView(Context cx) {
super(cx);
init();
}
public StyledTextView(Context cx, AttributeSet attrs) {
super(cx, attrs);
init()
}
public StyledTextView(Context cx, AttributeSet attrs, int defStyle) {
super(cx, attrs, defStyle);
init();
}
private void init() {
// Any other setup here (eg setting the default size
// or getting current value from shared preferences)
TextStyleHandler.getInstance().register(this);
}
public void onTextSizeChanged(float size) {
setTextSize(size);
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
TextStyleHandler.getInstance().unregister(this);
}
}
Triggering the style change event
This can be done from your activity, and will change the style of all registered views
TextStyleHandler.getInstance().setTextSize(size);

How to make a traditional Mongolian script ListView in Android

How do you make a horizontally scrolling ListView for vertical Mongolian script in Android apps?
Background
Android has fairly good support for many of the world's languages, even RTL languages like Arabic and Hebrew. However, there is no built in support for top-to-bottom languages like traditional Mongolian (which is still very much alive in Inner Mongolia and not to be confused with Cyrillic Mongolian). The following graphic shows the text direction with English added for clarity.
Since this functionality is not built into Android, it makes almost every single aspect of app development extremely difficult. This is expecially true with horizontal ListViews, which are not supported out of the box in Android. There is also very, very little information available online. There are a number of app developers for traditional Mongolian, but whether it is for commercial reasons or otherwise, they do not seem to make their code open source.
Because of these difficulties I would like to make a series of StackOverflow questions that can serve as a central place to collect answers for some of the more difficult programming problems related to traditional Mongolian app development. Even if you are not literate in Mongolian, your help reviewing the code, making comments and questions, giving answers or even up-voting the question would be appreciated.
Mongolian Horizontally Scrolling ListView with Vertical Script
A Mongolian ListView needs to have the following requirements:
Scrolls horizontally from left to right
Touch events work the same as with a normal ListView
Custom layouts are supported the same as in a normal ListView
Also needs to support everything that a Mongolian TextView would support:
Supports a traditional Mongolian font
Displays text vertically from top to bottom
Line wrapping goes from left to right.
Line breaks occur at a space (same as English)
The image below shows the basic functionality a Mongolian ListView should have:
My answer is below, but I welcome other ways of solving this problem.
Other related questions in this series:
How to make a traditional Mongolian script TextView in Android
How to make a traditional Mongolian script EditText in Android
More to come... (Toast, Dialog, Menu)
iOS:
How do you make a vertical text UILabel and UITextView for iOS in Swift?
Update
RecyclerViews have a horizontal layout. So it is relatively easy to put a Vertical Mongolian TextView inside one of these. Here is an example from mongol-library.
See this answer for a general solution to using a RecyclerView to make a horizontally scrolling list.
Old answer
It is quite unfortunate that horizontal ListViews are not provided by the Android API. There are a number of StackOverflow Q&As that talk about how to do them, though. Here are a couple samples:
How can I make a horizontal ListView in Android?
Horizontal ListView in Android?
But when I actually tried to implement these suggestions as well as incorporate Mongolian vertical text, I was having a terrible time. Somewhere in my search I found a slightly different answer. It was a class that rotated an entire layout. It did so by extending ViewGroup. In this way anything (including a ListView) can be put in the ViewGroup and it gets rotated. All the touch events work, too.
As I explained in my answer about Mongolian TextViews, it is not enough to simply rotate Mongolian text. That would be enough if every ListView item (or other text element in the ViewGroup) was only a single line, but rotating multiple lines make the line wrap go the wrong direction. However, mirroring the layout horizontally and also using a vertically mirrored font can overcome this, as is shown in the following image.
I adapted the rotated ViewGroup code to also do the horizontal mirroring.
public class MongolViewGroup extends ViewGroup {
private int angle = 90;
private final Matrix rotateMatrix = new Matrix();
private final Rect viewRectRotated = new Rect();
private final RectF tempRectF1 = new RectF();
private final RectF tempRectF2 = new RectF();
private final float[] viewTouchPoint = new float[2];
private final float[] childTouchPoint = new float[2];
private boolean angleChanged = true;
public MongolViewGroup(Context context) {
this(context, null);
}
public MongolViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
}
public View getView() {
return getChildAt(0);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final View view = getView();
if (view != null) {
measureChild(view, heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(resolveSize(view.getMeasuredHeight(), widthMeasureSpec),
resolveSize(view.getMeasuredWidth(), heightMeasureSpec));
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (angleChanged) {
final RectF layoutRect = tempRectF1;
final RectF layoutRectRotated = tempRectF2;
layoutRect.set(0, 0, right - left, bottom - top);
rotateMatrix.setRotate(angle, layoutRect.centerX(), layoutRect.centerY());
rotateMatrix.postScale(-1, 1);
rotateMatrix.mapRect(layoutRectRotated, layoutRect);
layoutRectRotated.round(viewRectRotated);
angleChanged = false;
}
final View view = getView();
if (view != null) {
view.layout(viewRectRotated.left, viewRectRotated.top, viewRectRotated.right,
viewRectRotated.bottom);
}
}
#Override
protected void dispatchDraw(Canvas canvas) {
canvas.save();
canvas.rotate(-angle, getWidth() / 2f, getHeight() / 2f);
canvas.scale(-1, 1);
super.dispatchDraw(canvas);
canvas.restore();
}
#Override
public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
invalidate();
return super.invalidateChildInParent(location, dirty);
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
viewTouchPoint[0] = event.getX();
viewTouchPoint[1] = event.getY();
rotateMatrix.mapPoints(childTouchPoint, viewTouchPoint);
event.setLocation(childTouchPoint[0], childTouchPoint[1]);
boolean result = super.dispatchTouchEvent(event);
event.setLocation(viewTouchPoint[0], viewTouchPoint[1]);
return result;
}
}
The Mongolian vertically mirrored font still needs to be set somewhere else, though. I find it easiest to make a custom TextView to do it:
public class MongolNonRotatedTextView extends TextView {
// This class does not rotate the textview. It only displays the Mongol font.
// For use with MongolLayout, which does all the rotation and mirroring.
// Constructors
public MongolNonRotatedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MongolNonRotatedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MongolNonRotatedTextView(Context context) {
super(context);
init();
}
// This class requires the mirrored Mongolian font to be in the assets/fonts folder
private void init() {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
"fonts/MongolMirroredFont.ttf");
setTypeface(tf);
}
}
Then the custom ListView item xml layout can look something like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rlListItem"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.MongolNonRotatedTextView
android:id="#+id/tvListViewText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"/>
</RelativeLayout>
Known issues:
If you look carefully at the image below you can see faint horizontal and vertical lines around the text. Although this image comes from another developer's app, I am getting the same artifacts in my app when I use the rotated ViewGroup (but not when I use the rotated TextView). If anyone knows where these are coming from, please leave me a comment!
This solution does not deal with rendering the Unicode text. Either you need to use non-Unicode text (discouraged) or you need to include a rendering engine in your app. (Android does not support OpenType smartfont rendering at this time. Hopefully this will change in the future. iOS, by comparison does support complex text rendering fonts.) See this link for a Unicode Mongolian rendering engine example.

Android 4.4 — Translucent status/navigation bars — fitsSystemWindows/clipToPadding don't work through fragment transactions

When using the translucent status and navigation bars from the new Android 4.4 KitKat APIs, setting fitsSystemWindows="true" and clipToPadding="false" to a ListView works initially. fitsSystemWindows="true" keeps the list under the action bar and above the navigation bar, clipToPadding="false" allows the list to scroll under the transparent navigation bar and makes the last item in the list scroll up just far enough to pass the navigation bar.
However, when you replace the content with another Fragment through a FragmentTransaction the effect of fitsSystemWindows goes away and the fragment goes under the action bar and navigation bar.
I have a codebase of demo source code here along with a downloadable APK as an example: https://github.com/afollestad/kitkat-transparency-demo. To see what I'm talking about, open the demo app from a device running KitKat, tap an item in the list (which will open another activity), and tap an item in the new activity that opens. The fragment that replaces the content goes under the action bar and clipToPadding doesn't work correctly (the navigation bar covers the last item in the list when you scroll all the way down).
Any ideas? Any clarification needed? I posted the before and after screenshots of my personal app being developed for my employer.
I struggled with the same problem yesterday. After thinking a lot, I found an elegant solution to this problem.
First, I saw the method requestFitSystemWindows() on ViewParent and I tried to call it in the fragment's onActivityCreated() (after the Fragment is attached to the view hierarchy) but sadly it had no effect. I would like to see a concrete example of how to use that method.
Then I found a neat workaround: I created a custom FitsSystemWindowsFrameLayout that I use as a fragment container in my layouts, as a drop-in replacement for a classic FrameLayout. What it does is memorizing the window insets when fitSystemWindows() is called by the system, then it propagates the call again to its child layout (the fragment layout) as soon as the fragment is added/attached.
Here's the full code:
public class FitsSystemWindowsFrameLayout extends FrameLayout {
private Rect windowInsets = new Rect();
private Rect tempInsets = new Rect();
public FitsSystemWindowsFrameLayout(Context context) {
super(context);
}
public FitsSystemWindowsFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FitsSystemWindowsFrameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected boolean fitSystemWindows(Rect insets) {
windowInsets.set(insets);
super.fitSystemWindows(insets);
return false;
}
#Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
super.addView(child, index, params);
tempInsets.set(windowInsets);
super.fitSystemWindows(tempInsets);
}
}
I think this is much simpler and more robust than hacks that try to determine the UI elements sizes by accessing hidden system properties which may vary over time and then manually apply padding to the elements.
I solved the issue by using the library I use the set the color of my translucent status bar.
The SystemBarConfig class of SystemBarTint (as seen here https://github.com/jgilfelt/SystemBarTint#systembarconfig) lets you get insets which I set as the padding to the list in every fragment, along with the use of clipToPadding="false" on the list.
I have details of what I've done on this post: http://mindofaandroiddev.wordpress.com/2013/12/28/making-the-status-bar-and-navigation-bar-transparent-with-a-listview-on-android-4-4-kitkat/
Okay, so this is incredibly weird. I just recently ran into this same issue except mine involves soft keyboard. It initially works but if I add fragment transaction, the android:fitsSystemWindows="true" no longer works. I tried all the solution here, none of them worked for me.
Here is my problem:
Instead of re-sizing my view, it pushes up my view and that is the problem.
However, I was lucky and accidentally stumbled into an answer that worked for me!
So here it is:
First of all, my app theme is: Theme.AppCompat.Light.NoActionBar (if that is relevant, maybe it is, android is weird).
Maurycy pointed something very interesting here, so I wanted to test what he said was true or not. What he said was true in my case as well...UNLESS you add this attribute to your activity in the android manifest of your app:
Once you add:
android:windowSoftInputMode="adjustResize"
to your activity, android:fitsSystemWindows="true" is no longer ignored after the fragment transaction!
However, I prefer you calling android:fitsSystemWindows="true" NOT on the root layout of your Fragment. One of the biggest places where this problem will occur is where if you have EditText or a ListView. If you are stuck in this predicament like I did, set android:fitsSystemWindows="true" in the child of the root layout like this:
YES, this solution works on all Lollipop and pre-lollipop devices.
And here is the proof:
It re-sizes instead of pushing the layout upwards.
So hopefully, I have helped someone who is on the same boat as me.
Thank you all very much!
A heads up for some people running into this problem.
A key piece of information with fitSystemWindows method which does a lot of the work:
This function's traversal down the hierarchy is depth-first. The same
content insets object is propagated down the hierarchy, so any changes
made to it will be seen by all following views (including potentially
ones above in the hierarchy since this is a depth-first traversal).
The first view that returns true will abort the entire traversal.
So if you have any other fragments with content views which have fitsSystemWindows set to true the flag will potentially be ignored. I would consider making your fragment container contain the fitsSystemWindows flag if possible. Otherwise manually add padding.
I've been struggling quite a bit with this as well.
I've seen all the responses here. Unfortunately none of them was fixing my problem 100% of the time.
The SystemBarConfig is not working always since it fails to detect the bar on some devices.
I gave a look at the source code and found where the insets are stored inside the window.
Rect insets = new Rect();
Window window = getActivity().getWindow();
try {
Class clazz = Class.forName("com.android.internal.policy.impl.PhoneWindow");
Field field = clazz.getDeclaredField("mDecor");
field.setAccessible(true);
Object decorView = field.get(window);
Field insetsField = decorView.getClass().getDeclaredField("mFrameOffsets");
insetsField.setAccessible(true);
insets = (Rect) insetsField.get(decorView);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
This is how to get them.
Apparently in Android L there'll be a nice method to get those insets but in the meantime this might be a good solution.
I encountered the same problem. When I replace Fragment.
The 'fitsSystemWindows' doesn't work.
I fixed by code add to your fragment
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
AndroidUtil.runOnUIThread(new Runnable() {
#Override
public void run() {
((ViewGroup) getView().getParent()).setFitsSystemWindows(true);
}
});
}
Combined with #BladeCoder answer i've created FittedFrameLayout class which does two things:
it doesn't add padding for itself
it scan through all views inside its container and add padding for them, but stops on the lowest layer (if fitssystemwindows flag is found it won't scan child deeper, but still on same depth or below).
public class FittedFrameLayout extends FrameLayout {
private Rect insets = new Rect();
public FittedFrameLayout(Context context) {
super(context);
}
public FittedFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FittedFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FittedFrameLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
protected void setChildPadding(View view, Rect insets){
if(!(view instanceof ViewGroup))
return;
ViewGroup parent = (ViewGroup) view;
if (parent instanceof FittedFrameLayout)
((FittedFrameLayout)parent).fitSystemWindows(insets);
else{
if( ViewCompat.getFitsSystemWindows(parent))
parent.setPadding(insets.left,insets.top,insets.right,insets.bottom);
else{
for (int i = 0, z = parent.getChildCount(); i < z; i++)
setChildPadding(parent.getChildAt(i), insets);
}
}
}
#Override
protected boolean fitSystemWindows(Rect insets) {
this.insets = insets;
for (int i = 0, z = getChildCount(); i < z; i++)
setChildPadding(getChildAt(i), insets);
return true;
}
#Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
super.addView(child, index, params);
setChildPadding(child, insets);
}
}
I have resolve this question in 4.4
if(test){
Log.d(TAG, "fit true ");
relativeLayout.setFitsSystemWindows(true);
relativeLayout.requestFitSystemWindows();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}else {
Log.d(TAG, "fit false");
relativeLayout.setFitsSystemWindows(false);
relativeLayout.requestFitSystemWindows();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}

Android: Using FEATURE_NO_TITLE with custom ViewGroup leaves space on top of the window

I am trying to create a custom ViewGroup, and I want to use it with a full screen application. I am using the "requestWindowFeature(Window.FEATURE_NO_TITLE)" to hide the title bar. The title bar is not showing, but it still consuming space on top of the window.
The image above was generated with the following code:
public class CustomLayoutTestActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Button b = new Button(this);
b.setText("Hello");
CustomLayout layout = new CustomLayout(this);
layout.addView(b);
setContentView(layout);
}
}
public class CustomLayout extends ViewGroup {
public CustomLayout(Context context) {
super(context);
}
public CustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.i("CustomLayout", "changed="+changed+" l="+l+" t="+t+" r="+r+" b="+b);
final int childCount = getChildCount();
for (int i = 0; i < childCount; ++i) {
final View v = getChildAt(i);
v.layout(l, t, r, b);
}
}
}
(The full Eclipse project is here)
It is interesting to see that it is the Android that is given this space for my custom layout. I am setting the CustomLayout as the root layout of my Activity. In the Log in the "onLayout" is receiving "t=25", and that is what is pushing my layout down. What I don't know is what I am doing wrong that makes Android the "t=25" (which is exactly the height of the title bar).
I am running this code in the Android SDK 2.1, but I also happens in Android 2.2.
EDIT: If I change the CustomLayout class for some default layout (such as LinearLayout), the space disappears. Of course, the default layouts of Android SDK don't create the layout I am trying to create, so that is why I am creating one.
Although the layout I am creating is somewhat complex, this is the smallest code I could create reproducing the problem I have with my layout.
It's not a full answer, but in the meantime you can work around the problem by wrapping your custom layout in a <FrameLayout />
Also, it's worth noting that your layout extends beyond the bottom of the screen. It's shifted down by the title bar height (38 pixels in my emulator)
Edit: Got it. onLayout() (and the corresponding layout() method) specify that the coordinate are not relative to the screen origin, they're relative to the parent ( http://developer.android.com/reference/android/view/View.html#layout%28int,%20int,%20int,%20int%29 ). So the system is telling you that you're at relative coordinates (0, 38), and you're adding it when passing that down to your child, which means that you're saying that your child is at screen coordinates (0, 76), causing the gap.
What you actually want to do is:
v.layout(0, 0, r - l, b - t);
That will put your child Views aligned with the top left corner of your View, with the same width and height as your view.
I had the same issue with a FrameLayout in 2.2
I fixed it by adding android:layout_gravity="top" to the FrameLayout

Categories

Resources