Square ImageView in the center of the screen - java

I would like to position ImageView in the center of the screen and set the width and height of the ImageView to the width of the screen.
I tried this, but the width of the ImageView is not equal to the width of the screen and ImageView is positioned in the top left corner:
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams((int)dpWidth, (int)dpWidth);
imageView.setLayoutParams(layoutParams);
In xml ImageView is in the center of the screen:
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

In Java code, setLayoutParams is overriding layout rules (params starting with layout_) you defined in xml.
You need to add the rules to keep centering the image.
Also LayoutParams will take integer in "pixels" not "dp".
So try this -
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels;
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams((int)dpWidth, (int)dpWidth);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
imageView.setLayoutParams(layoutParams);
Also, you might want to play with scaleType to let image fill the space.
Please check here for the available scaleType.
http://developer.android.com/reference/android/widget/ImageView.ScaleType.html

Related

How to design drawable left icon as circular (added using setCompoundDrawablesWithIntrinsicBounds) in Textview using java code (not xml)

I have a text view with icon rendered in the TextView. It has an image. I have set on the left of the text. But I need to set the icon as a circular shape.
How can I design this in java?
My code which set on the left side.
textview.setCompoundDrawablesWithIntrinsicBounds(
image, 0, 0, 0);
How can I design the circular image for the above textview drawableleft image.
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_vertical"
android:ellipsize="end"
android:layout_marginTop="5dp"
android:layout_marginBottom="-10dp"
android:gravity="center"
android:layout_marginLeft="15dp"
android:minHeight="24dp"
android:paddingLeft="#dimen/spacing_d2"
android:paddingRight="#dimen/spacing_d2"
android:tag="#string/tag_font_h_regular"
android:fontFamily="#font/cachetbook"
android:textColor="#color/white_new"
android:textSize="12dp"
tools:text="Universal Orlando Resort"/>
Load your image
You need to load your image as a bitmap. If you are taking if from your drawable, you can see How to convert a Drawable to a Bitmap?.
Resize it
You can resize your bitmap to scale it to fit your textview as you wish. See How to Resize a Bitmap in Android?.
Make the corner rounded
According to this post you can found the code to make corner rounded
Code example
// Load your drawable
Drawable drawable = ContextCompat.getDrawable(this,R.drawable.ic_launcher_background);
// Convert it to a bitmap
Bitmap bitmap = Bitmap.createScaledBitmap(drawableToBitmap((drawable)),50,50,false);
// Make the corner rounded
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
final float roundPx = (float) bitmap.getWidth() * 90f;
roundedBitmapDrawable.setCornerRadius(roundPx);
// Apply it to the TextView
((TextView) findViewById(R.id.test)).setCompoundDrawablesWithIntrinsicBounds(
roundedBitmapDrawable, null, null, null);
Output
Note
I do not know why you decided to choose to do it programmatically, but I would not recommand it, it is harder to control the view and how things are positionned.

Set Layout width percentage of the total screen width

Is there's way to set Button width 50% of the total screen size (from java code).
I have found a few answers but i would like to change Button size with java code instead of XML.
Try this out..
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
ViewGroup.LayoutParams params = yourButton.getLayoutParams();
params.width = metrics.widthPixels;
try {
double ratio = 0.5;
params.height = Double.valueOf(ratio * height).intValue();
yourButton.setLayoutParams(params);
} catch (Exception e) {
e.printStackTrace();
}
Many ways to achieve this, you could try like below:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
ViewGroup.LayoutParams params= yourBtn.getLayoutParams();
params.width= width * 1/2;
yourBtn.setLayoutParams(params);
yourBtn.requestLayout();
It's so simple just do.
button.getLayoutParams().width = Resources.getSystem().getDisplayMetrics().widthPixels/2;
I hope it Helps
possible with of Guideline constraint
Guideline
Utility class representing a Guideline helper object for
ConstraintLayout. Helper objects are not displayed on device (they are
marked as View.GONE) and are only used for layout purposes. They only
work within a ConstraintLayout.
A Guideline can be either horizontal or vertical:
Vertical Guidelines have a width of zero and the height of their
ConstraintLayout parent Horizontal Guidelines have a height of zero
and the width of their ConstraintLayout parent Positioning a Guideline
is possible in three different ways:
specifying a fixed distance from the left or the top of a layout
(layout_constraintGuide_begin) specifying a fixed distance from the
right or the bottom of a layout (layout_constraintGuide_end)
specifying a percentage of the width or the height of a layout
(layout_constraintGuide_percent) Widgets can then be constrained to
a Guideline, allowing multiple widgets to be positioned easily from
one Guideline, or allowing reactive layout behavior by using percent
positioning.
See the list of attributes in ConstraintLayout.LayoutParams to set a
Guideline in XML, as well as the corresponding
ConstraintSet.setGuidelineBegin(int, int),
ConstraintSet.setGuidelineEnd(int, int) and
ConstraintSet.setGuidelinePercent(int, float) functions in
ConstraintSet.
<android.support.constraint.Guideline
android:id="#+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.50" />
**
Example
**
<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">
<android.support.constraint.Guideline
android:id="#+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.50" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintBottom_toTopOf="#+id/guideline4"
app:layout_constraintTop_toTopOf="#+id/guideline3"
tools:layout_editor_absoluteX="104dp" />
<android.support.constraint.Guideline
android:id="#+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.80" />
</android.support.constraint.ConstraintLayout>
Example with Layout height 50% of screen
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toTopOf="#+id/guideline4"
app:layout_constraintTop_toTopOf="parent">
</RelativeLayout>
<android.support.constraint.Guideline
android:id="#+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.50" />
2nd Way
getDefaultDisplay ()
public abstract Display getDefaultDisplay () Returns the Display upon
which this WindowManager instance will create new windows.
Despite the name of this method, the display that is returned is not
necessarily the primary display of the system (see
Display.DEFAULT_DISPLAY). The returned display could instead be a
secondary display that this window manager instance is managing. Think
of it as the display that this WindowManager instance uses by default.
To create windows on a different display, you need to obtain a
WindowManager for that Display. (See the WindowManager class
documentation for more information.)
Display mDisplay = getWindowManager().getDefaultDisplay();
final int width = mDisplay.getWidth();
final int height = mDisplay.getHeight();
// now simple height/2 use it as u want
something like this perhaps? Not sure if it will work exactly as you want it but thats the general idea of it
Configuration configuration = getActivity().getResources().getConfiguration();
int screenWidthDp = configuration.screenWidthDp;
final float scale = context.getResources().getDisplayMetrics().density;
int pixels = (int) (screenWidthDp * scale);
button1.setWidth(pixels*0.5);
Try
LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(left, top, right, bottom);
yourbutton.setLayoutParams(params);
Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
yourdpmeasure,
r.getDisplayMetrics());

Adding an ImageView at a random position in a LinearLayout

I want to add image views dynamically to a full screen linear layout. I have written some code but some image views are either partially or totally going outside the screen. Some times image views are well within the phone screen.
How can I ensure that they remain totally inside the screen.
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final int widthArea = displayMetrics.widthPixels;
final int heightArea = displayMetrics.heightPixels;
final LinearLayout home = (LinearLayout) findViewById(R.id.llHome);
ImageView imgView = new ImageView(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(200, 200);
imgView.setLayoutParams(lp);
imgView.setImageResource(R.drawable.img_1);
imgView.setX(r.nextInt(widthArea));
imgView.setY(r.nextInt(heightArea));
home.addView(imgView);
You should take into account the dimension of the image itself. Settings X and Y place its starting point within the screen but it might leak on a side.
First, load your image as a Drawable, then include drawable.getWidth() (and maybe even height, that depends on your layout) to your X position.
imgView.setX(r.nextInt(widthArea - drawable.getWidth()) + drawable.getWidth());

How to write XML code for width and heigh in Java

XML code
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/pz"
android:layout_marginTop="5dp" />
I wrote it like this in java
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(R.drawable.pz);
DisplayMetrics displaymetrics = new DisplayMetrics();
MainActivity.this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int height = 300;
imageView.setLayoutParams(new ViewGroup.LayoutParams(width, height));
imageView.setId(i + 1);
li.addView(imageView);
But it looks strange , i want to change height to eg. 200 , instead of changing height it change width.Is there any better way to make it i just want width to MATCH_PARENT and height to be 200dp?
if you want to set any layout parameter to wrap_content or match_parent you should set ViewGroup.LayoutParams.MATCH_PARENT orViewGroup.LayoutParams.MATCH_PARENT constants for constructor parameters
and the constructor gets parameters in px so you have to change it to dp you can use this link

How to set relativelayout height equal to its width?

I searched a lot to find out how its gonna work and I got nothing.
I found some java code to do it dynamically but didn't work ant of theme and when opening the program, show a force close.
this is my code:
<LinearLayout android:baselineAligned="false"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="#+id/rlv1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_weight="1"
android:background="#drawable/rectengle2" >
</RelativeLayout>
<RelativeLayout
android:id="#+id/rlv2"
android:layout_width="fill_parent"
android:layout_weight="1"
android:background="#drawable/rectengle" >
</RelativeLayout>
</LinearLayout>
as you can see I created a rectangle shape and used it in a relative layout with a lineaer layout as parent and i splitted that linear layout verticali to two part for each relative layout.
now i want to set these relative layout height equal to its width to get a pure square rectangle.
i tried many way but ... can help me any guy please?? thnaks..
The simplest solution, imo, is to subclass RelativeLayout, and override onMeasure, providing to the super the same size for width and height. For instance
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
as pointed out by #ZakTaccardi, declare it in your layout like
<com.example.subclassrelativelayout
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Finally I myself found out what to do in this situation. so i'm gonna explain how to solve for those who have or will have my problem.
in my xml ui file I set layout_weight=1 for a pair of relative layout that were in a linear layout to be splitted in the screen and actually width of each of them be the half of my screen width. my problem was about height and i tried many java codes to set relative layout height equals to its width.
finally i calculated the screen width in "DP" Term and set every relative layout's height to this. this is the solved code:
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);
float density = getResources().getDisplayMetrics().density;
float dpWidth = outMetrics.widthPixels / density;
RelativeLayout Rl1 = (RelativeLayout) findViewById(R.id.rlv1);
Rl1.getLayoutParams().height = (int) (dpWidth);
RelativeLayout Rl2 = (RelativeLayout) findViewById(R.id.rlv2);
Rl2.getLayoutParams().height = (int) (dpWidth);
so i got a pure square! Enjoy it. Thanks

Categories

Resources