So I'm totally lost now I have problems with Text size ruing my UI when user sets his font size through Accessibility -> Font size to Huge so for quick fix I decided to change all text sizes to dp instead of sp that text would always be same size but on some places textviews even when textsize is set to dp resizes any idea why??
Here is button with text size set to dp which maintains font size even after changing through accessibility
<Button
android:id="#+id/video_button"
android:textSize="16dp"
android:layout_marginTop="10dp"
android:layout_height="30dp"
android:layout_width="180dp"
android:layout_centerHorizontal="true"
android:layout_below="#+id/webshop_button"
android:text="#string/button_3dvideo_text"/>
And here is textView which ignores textSize even after setting it to dp:
<TextView
android:id="#+id/about"
android:gravity="center"
android:textSize="16dp"
android:layout_above="#+id/footer"
android:layout_marginBottom="20dp"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/color_white"
android:text="#string/about"/>
I have a solution for this which will make the font size non changeable in your app :
public void adjustFontScale(Configuration configuration) {
configuration.fontScale = (float) 1;
DisplayMetrics metrics = getResources().getDisplayMetrics();
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
metrics.scaledDensity = configuration.fontScale * metrics.density;
getBaseContext().getResources().updateConfiguration(configuration, metrics);
}
Call this method in onCreate of your every Activity or you can make a Base Activity:
adjustFontScale(getResources().getConfiguration());
You can change the fontScale according to your needs.
Hope this helps.
May be try to use this Not sure whether its going to help you.
DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
float dp = 20f;
float fpixels = metrics.density * dp;
int pixels = (int) (fpixels + 0.5f);
Edit_click.setTextSize(pixels);
Related
I want to set height and width for framelayout , if give values in java code using setlayoutparams its showing very small box, but in XML its showing properly.
This is my java code
FrameLayout frameLayout2= (FrameLayout) light.findViewById(R.id.frameLayout2);
ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(300, 300);
frameLayout2.setLayoutParams(lp);
this is my xml:
Note:Constraint layout is my parent
<android.support.constraint.ConstraintLayout
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=".LightPlaceFragment"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp"
android:background="#color/colorAccent">
<FrameLayout
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintHorizontal_bias="0.882"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/l_width"
app:layout_constraintVertical_bias="0.162"
android:id="#+id/frameLayout2">
<include
android:id="#+id/other"
android:layout_width="300dp"
android:layout_height="200dp"
android:visibility="visible"
layout="#layout/sample1" />
</FrameLayout>
</android.support.constraint.ConstraintLayout>
values given in xml so its showing properly:
Result using XML
Values in given java code so its showing very smallbox
Result using Java
How can I change the framelayout width and height programatically?
Please help me.
Try this
FrameLayout frameLayout2= (FrameLayout) light.findViewById(R.id.frameLayout2);
ConstraintLayout.LayoutParams oldParams = (ConstraintLayout.LayoutParams) frameLayout2.getLayoutParams();
oldParams.width=400;
oldParams.height=500;
frameLayout2.setLayoutParams(oldParams);
OR this
FrameLayout frameLayout2= (FrameLayout) light.findViewById(R.id.frameLayout2);
ConstraintLayout.LayoutParams oldParams= new ConstraintLayout.LayoutParams(300,300);
frameLayout2.setLayoutParams(oldParams);
Happened with me as well.
After spending so much time, I got to know that on setting height and width programmatically it takes in PX (pixel) not in dp which we set in XML.
So you need to convert dimension into PX from dp first using display factor like this.
val scale: Float = resources.displayMetrics.density
val resizedInPx = (widthInDp * scale + 0.5f).toInt() // dp to px
Where widthInDp is the desired dp you want to set like 300
Usage
val params: ViewGroup.LayoutParams = yourlayout.layoutParams
params.width = (widthInDp * scale + 0.5f).toInt() // dp to px
params.height = (heightInDp * scale + 0.5f).toInt() // dp to px
layout!!.setLayoutParams(params)
Use this
FrameLayout frameLayout2= (FrameLayout) light.findViewById(R.id.frameLayout2);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(300, 300);
frameLayout2.setLayoutParams(lp);
(KOTLIN) If you need to update the width and height only, you can use the below method:
private fun resizeView(view: View) {
val size = resources.getDimension(R.dimen.view_size).toInt()
view.layoutParams.width = size
view.layoutParams.height = size
//or (but be careful because this will change all the constraints you added in the xml file)
val newLayoutParams = ConstraintLayout.LayoutParams(size, size)
view.layoutParams = newLayoutParams
}
I want to change the ExpandableListView group indicator to right with padding.
I used custom adapter to load data to ExpandableListView.
This is my ExpandableListView xml.
<ExpandableListView
android:id="#+id/Ex_offers"
android:layout_width="250dp"
android:layout_height="400dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:childDivider="#00000000"
android:groupIndicator="#drawable/settings_selector"
android:listSelector="#android:color/transparent">
</ExpandableListView>
This is GroupView xml
<TextView
android:id="#+id/lblListHeadertwo"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#drawable/transperant_bar"
android:fontFamily="Lato"
android:paddingLeft="15dp"
android:textColor="#daac56"
android:textStyle="bold"
android:textSize="17sp"
android:paddingTop="8dp" />
This is ChildView xml
<TextView
android:id="#+id/text_offers"
android:layout_width="300dp"
android:layout_height="20dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/transperant_bar"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
android:textColor="#daac56"
android:textSize="14sp"/>
<ImageView
android:id="#+id/img"
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_marginLeft="12dp"/>
This is the output image, I want to set margin to this indicator.
setIndicatorBounds(int, int) does not work properly for Android 4.3.
They introduced a new method setIndicatorBoundsRelative(int, int) which works ok for 4.3.
public int GetPixelFromDips(float pixels) {
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
return (int) (pixels * scale + 0.5f);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
explvList.setIndicatorBounds(width-GetPixelFromDips(35), width-GetPixelFromDips(5));
} else {
explvList.setIndicatorBoundsRelative(width-GetPixelFromDips(35), width-GetPixelFromDips(5));
}
}
private void setGroupIndicatorToRight() {
/* Get the screen width */
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
expandableList.setIndicatorBounds(width - getDipsFromPixel(35), width - getDipsFromPixel(5));
}
// Convert pixel to dip
public int getDipsFromPixel(float pixels) {
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
return (int) (pixels * scale + 250.5f);
}
If you want to move indicator to right Just create a dimen in res folder. It will be like that:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="my_value">350dp</dimen>
</resources>
Then in the <ExpandableListView/> add like that:
<ExpandableListView
...
android:indicatorLeft="#dimen/my_value"
.../>
You can change the dp according to device settings
A sprite on my android game is set to fall by 5 pixels every 100 milliseconds, this works fine the only problem is that the ImageView itself is only 53dp high, if I make it any bigger the image inside scales with it. Since the ImageView is only 53dp high the image disappears after 1100 milliseconds as it scrolls outside the boundaries of the imageview.
I need the layout height of the ImageView to fill_parent but I need the image to stay the same size instead of scaling with it, here's my current code:
<ImageView
android:id="#+id/blueman"
android:layout_width="0dip"
android:layout_height="53dp"
android:paddingRight="300dp"
android:layout_weight="0.03"
android:src="#drawable/fall" />
Thanks in advance :)
since you didn't give the full code of the layout, I'll make some assumptions...
you're talking about setting your sprite's height to the screen's height without scaling?
There should be a difference between your screen size (that is the root layout item) and the sprites in it. I guess you declared your layout as...:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="?gameBackground"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btTap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="350dp"
android:background="#drawable/tap"
android:visibility="visible" />
<Button
android:id="#+id/btCellR1C1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="490dp"
android:layout_marginTop="155dp"
android:background="#drawable/cell_red" />
The only thing I had to cope with, was the scaling of my sprites depending on the device's resolution with such a method:
public static void scaleView(View view, int top, int left, int width,
int height) {
top = Math.round(top * scaleY);
left = Math.round(left * scaleX);
width = Math.round(width * scaleX);
height = Math.round(height * scaleY);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.height = height;
params.width = width;
params.topMargin = top;
params.leftMargin = left;
view.setLayoutParams(params);
view.setSoundEffectsEnabled(false);
}
Please give us more details to help you
Best regards
Serge
Hi I'm developing an app on android and I have some layouts where I would like to have an image that fills the screen-width in landscape mode. On top of that, i want some buttons on specific places.
I used a scrollview (because the image doesn't fit in height if it fills the width of the screen), with a relative layout within.
In that relative layout, I put the imageview and the buttons. The image fills the width and wraps the content for the height. The buttons are placed through setting the left and top margins within the relative layout.
Everything is looking good on the phone i tested it with, but when i test on a different device (other screen size and density) all buttons are on the wrong place and aren't big enough anymore.
How can i change this, so that all proportions stay the same? The buttons have to be in the exact same position and have to be the same size, in comparison with the image.
My code:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/svCentralAmerica"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true" >
<RelativeLayout
android:id="#+id/rlCentralAmerica"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/ivCentralAmerica"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:src="#drawable/mapcentralamerica" />
<Button
android:id="#+id/mexu"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="33dp"
android:background="#drawable/usa_y"
android:onClick="onCountryClick"
android:paddingTop="3dp"
android:scaleType="fitCenter"
android:tag="1;U"
android:text="2"
android:textColor="#color/Black"
android:textSize="15sp"
android:textStyle="bold" />
<Button
android:id="#+id/mexr"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_alignTop="#id/mexu"
android:layout_marginLeft="4dp"
android:layout_toRightOf="#id/mexu"
android:background="#drawable/russia_n"
android:onClick="onCountryClick"
android:paddingTop="18dp"
android:scaleType="fitCenter"
android:tag="1;R"
android:text="3"
android:textColor="#color/Red"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
</ScrollView>
I have actually done what you're thinking of. Unfortunately, if you want exact control of the positioning on any screen size, and an exact aspect ratio, then you're going to have to position resources programmatically. If you use xml, you can come pretty close, but won't have precise positioning control. For a beginner, positioning programmatically can be tedious. Since you're only positioning a couple of buttons here and there, it shouldn't be too much of a hassle.
How I did it: get the screenwidth and screenheight programmatically. Then calculate the aspect ratio of your button. Next, calculate the position of the button in relation to the screenwidth and screenheight (this would be in %). With all this info, you should be able to position buttons exactly where you want it on any screen size with a particular orientation. I would recommend positioning everything else on xml and do only the buttons programmatically. On orientation change, you will need to recalculate everything again, which can be annoying. I would recommend that you stick with 1 orientation and maybe support multiple orientations later.
I use these helper functions to move my buttons around based on the percentage of the screen height and width. First I layout the screen for a 320 x 480 screen in graphical layout to create the xml, then move the buttons in my onCreate method.
Here are the imports I used:
import android.app.Activity;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.content.Context;
import android.util.Log;
Here are the calls to move the buttons in onCreate:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moveBtn(0.1843,0.1187,0.128,0.7375,R.id.credits_button);
moveBtn(0.1843,0.1187,0.3125,0.7375,R.id.website_button);
moveBtn(0.1843,0.1187,0.5,0.7375,R.id.facebook_button);
moveBtn(0.1843,0.1187,0.6906,0.7375,R.id.support_button);
}
Here are the helper functions:
//----------------------------------------------------------------------------------------------
// public void moveBtn(double percent_width, double percent_height, double percent_x, double percent_y, int myObject)
//----------------------------------------------------------------------------------------------
public void moveBtn(double percent_width, double percent_height, double percent_x, double percent_y, int myObject) {
int width = (int)Math.round((ScWth(this) * percent_width));
int height = (int)Math.round((ScHgt(this) * percent_height));
int x = (int)Math.round((ScWth(this) * percent_x));
int y = (int)Math.round((ScHgt(this) * percent_y));
Log.d(TAG, "Object: " + myObject + "/Width: " + width + "/Height: "+ height + "/x: "+ x + "/y: "+ y);
AbsoluteLayout.LayoutParams myParam = new AbsoluteLayout.LayoutParams(width, height, x, y);
Button thisButton = (Button)findViewById(myObject);
thisButton.setLayoutParams(myParam);
}
//----------------------------------------------------------------------------------------------
// public static double ScWth(Context context)
//----------------------------------------------------------------------------------------------
//return the screen width of the device
public static double ScWth(Context context){
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
return display.getWidth();
}
//----------------------------------------------------------------------------------------------
// public static double ScHgt(Context context)
//----------------------------------------------------------------------------------------------
//return the screen height of the device
public static double ScHgt(Context context){
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
return display.getHeight();
}
I hope it helps someone.
I want to create a toolbar in my app, and I am wondering what is the standard height for the toolbar in android?
I want it to be big enough for a finger, but not huge. Is there standard size?
Its best to use ?attr/actionBarSize as #Jaison Brooks commented.
In the material guidelines, suggested height is 56dp:
Toolbar: 56dp
The recommended minimum size for touchable elements is 48 dp, see this page for more detailed metrics.
In addition to #vedant1811 answer, you can programmatically obtain actionBarSize from attrs:
TypedValue tv = new TypedValue();
if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
}
You can use the following method to get the AppBar height programatically
private static final int DEFAULT_TOOLBAR_HEIGHT = 56;
private static int toolBarHeight = -1;
public static int getToolBarHeight(Context context) {
if (toolBarHeight > 0) {
return toolBarHeight;
}
final Resources resources = context.getResources();
final int resourceId = resources.getIdentifier("action_bar_size", "dimen", "android");
toolBarHeight = resourceId > 0 ?
resources.getDimensionPixelSize(resourceId) :
(int) convertDpToPixel(DEFAULT_TOOLBAR_HEIGHT);
return toolBarHeight;
}
public static float convertDpToPixel(Context context, float dp) {
float scale = context.getResources().getDisplayMetrics().density;
return dp * scale + 0.5f;
}
you can use the toolbar widget that already exist in android and put the height wrap_content , so it will better to get the default size that come with it.
here
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#color/dark_cerulean">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingEnd="16dp"
android:paddingStart="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="end"
android:gravity="end"
android:layout_marginEnd="16dp"
android:textColor="#color/white"
android:id="#+id/toolbar_title" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/image1"
android:id="#+id/image"/>
</LinearLayout>
</android.support.v7.widget.Toolbar>
For phones it is 56dp and for large devices like tablets which you have more spaces it could be 64dp
Here's my Kotlin solution
fun getActionBarHeight(activity: Activity): Int {
val typedValue = TypedValue()
if (activity.theme.resolveAttribute(
android.R.attr.actionBarSize,
typedValue,
true
)
) return TypedValue.complexToDimensionPixelSize(
typedValue.data,
activity.resources.displayMetrics
)
return 0
}