Set big image to background - java

I got current wallpaper as below:
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
Drawable wallpaperDrawable = wallpaperManager.getDrawable();
now my current wallpaper (1152 X 1536)
I try to put it as background to activity but in width does not as screen width.
ImageView rv = (ImageView) findViewById(R.id.main);
rv.setBackgroundDrawable(wallpaperDrawable);
how I do it?
please help me.
thanks in advance

Did you set your RelativeLayout size is match_parent?
Then you can set Image fit to width side programmatically :
int width = getWindowManager().getDefaultDisplay().getWidth(); //get window width
yourIMG.getLayoutParams().width = width; // set Image width = window width

goto your xml for the current activity:
in that under the LinearLayout or Relative Layout add this line :
android:background = "#drawable/img_name"
and add the image to your drawable.

Related

Set the margins of an imageView by programming inside a constraintLayout

I am trying to program the margin of the ImageView inside the ConstraniLayout2 with this code
ConstraintLayout.LayoutParams newLayoutParams = (ConstraintLayout.LayoutParams)
imageView.getLayoutParams();
newLayoutParams.topMargin = 140;
newLayoutParams.leftMargin = 400;
newLayoutParams.rightMargin = 0;
newLayoutParams.bottomMargin = 0;
imageView.setLayoutParams(newLayoutParams);
With this code I program the site of the imageView but of the entire screen of the smartphone.
How can I program the imageView to switch places with the constrainLayout2 references?
You can also try to set the margin using ConstraintSet.
Below is a snippet you can try
val constraintSet = ConstraintSet()
constraintSet.clone(constraintLayoutId)
val marginTop = context.getDimension(10f)
constraintSet.setMargin(R.id. imageView, ConstraintSet.TOP, marginTop)
constraintSet.applyTo(constraintLayoutId)
fun Context.getDimension(value: Float): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, value, this.resources.displayMetrics).toInt()
}

Vector drawable in any location within text view (not outside of it)

Is there a way to add a drawable in any position within a text view programmatically without having to position it on a particular side of a text view? The following code works when using unicode character but I want to try the same with a vector drawable.
textView.text = getString(R.string.app_settings) + " \u2794 " + getString(R.string.display)
For me, ImageSpan works.
You can put a delimiter and replace it with the drawable. I used a google icon in this example
:
Code with delimiter replacement:
Drawable drawable = ContextCompat.getDrawable(this, R.drawable.google_icon);
drawable.setBounds(0, 0, 100,100);
String text = " Google %google_icon% icon";
String delimiter = "%google_icon%";
int icon_index = text.indexOf("%google_icon%");
text = text.replace(delimiter," ");
Spannable span = new SpannableString(text);
ImageSpan image = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
span.setSpan(image, icon_index, icon_index+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(span);
Or, you can place the drawable on any index like:
span.setSpan(image, start_index, end_index, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
PS: I used Display1 in text appearance. You need to change drawable bounds according to your own needs.

How to draw specific drawable resource programmatically?

I have a set of images in my drawable resources. Now I want to be able to change a placeholder image accordingly with image.setImageResource(R.id.name_of_image) programmatically.
My ImageView is defined as ImageView image = findViewById(R.id.placeholder);
How would I do this? I have tried getIdentifier but that didn't work.
The images have the format Name.jpg
EDIT:
I currently have the following construction:
int resID = getResources().getIdentifier(name.toLowerCase(), "drawable", this.getPackageName());
ImageView image = findViewById(R.id.placeholder);
image.setImageResource(resID);
I have changed the image name to lowercase and it is now a png file.
Your images has to be in png format (prefered by android) and must contain only lowercase letters and digits ([a-z0-9_.].
Then you can use
image.setImageResource(R.drawable.name_of_image);
You can get the name of the drawable with this:
String name = context.getResources().getResourceEntryName(R.drawable.name_of_image);
To get the drawable with the string name:
int id = context.getResources().getIdentifier("name_of_image", "drawable", context.getPackageName());
image.setImageResource(id);

Simple image gallery with HorizontalScrollView

I'm writing an image gallery with horizontal scrolling. Images must be added programatically.
I use a custom horizontal scroll view to process and add images as in the following code:
public void setViewList(Integer linearLayoutId, Integer[] imageIdList,
Activity activity) {
displayMetrics = ImageUtils.getDisplayMetric(activity);
LinearLayout ll = (LinearLayout) findViewById(linearLayoutId);
for (Integer imgId : imageIdList) {
ImageView imageView = new ImageView(getContext());
imageView.setImageResource(imgId);
imageView.setScaleType(ImageView.ScaleType.MATRIX);
Integer[] displayMetrics = ImageUtils.getDisplayMetric(activity);
ImageUtils.scaleImage(imageView, displayMetrics[0], displayMetrics[1]);
Integer[] dstDimension = ImageUtils.createDimension();
ImageUtils.getImageSize(imageView, dstDimension);
getImageSizeList().add(dstDimension);
ll.addView(imageView);
}
}
As you can see I scale an image with use the following method (call ImageUtils.scaleImage(imageView, displayMetrics[0], displayMetrics[1])):
public static void scaleImage(ImageView imView, int screenWidth, int screenHeight) {
Drawable temp = imView.getDrawable();
Bitmap imBitmap = ((BitmapDrawable)temp).getBitmap();
int imWidth = imBitmap.getWidth();
int imHeight = imBitmap.getHeight();
float xScale = ((float) screenWidth) / imWidth;
float yScale = ((float) screenHeight) / imHeight;
float scale = xScale <= yScale ? xScale : yScale;
Matrix scaleMatrix = new Matrix();
scaleMatrix.postScale(scale, scale);
Bitmap scBitmap = Bitmap.createBitmap(imBitmap, 0, 0, imWidth, imHeight, scaleMatrix, true);
BitmapDrawable scDrBitmap = new BitmapDrawable(imView.getResources(), scBitmap);
imView.setImageDrawable(scDrBitmap);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
);
layoutParams.gravity = Gravity.CENTER;
imView.setLayoutParams(layoutParams);
}
My main.xml layout is pretty simple:
<?xml version="1.0" encoding="utf-8"?>
<android.lessons.custom_horizontal_scroll.CustomHorizontalScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/horizontalScrollView"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout android:orientation="horizontal"
android:id="#+id/mainLayout"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.lessons.custom_horizontal_scroll.CustomHorizontalScrollView>
Where the android.lessons.custom_horizontal_scroll.CustomHorizontalScrollView is implementation of a simple custom HorizontalScrollView.
For testing I use Samsung Galaxy S3 and images with the following resolution: (1) 1290*990 (2) 1221*900. What it looks like:
In many cases everything is displayed fine but from time to time I get the wrong result: the first image divides a screen with the following one at app start time and I don't have any idea why it happens.
Thanks for help.
I think you should use ViewPager from the support library v4 rather than this custom horizontal scroll view in this case. It's designed for that purpose.
Here is how to use it https://developer.android.com/training/animation/screen-slide.html.
The problem was resolved with use gravity = Gravity.FILL_HORIZONTAL | Gravity.CENTER_VERTICAL, that i set programmatically on a image view (method ImageUtils.scaleImage).

How to programmatically set drawableLeft on Android button?

I'm dynamically creating buttons. I styled them using XML first, and I'm trying to take the XML below and make it programattic.
<Button
android:id="#+id/buttonIdDoesntMatter"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="buttonName"
android:drawableLeft="#drawable/imageWillChange"
android:onClick="listener"
android:layout_width="fill_parent">
</Button>
This is what I have so far. I can do everything but the drawable.
linear = (LinearLayout) findViewById(R.id.LinearView);
Button button = new Button(this);
button.setText("Button");
button.setOnClickListener(listener);
button.setLayoutParams(
new LayoutParams(
android.view.ViewGroup.LayoutParams.FILL_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT
)
);
linear.addView(button);
You can use the setCompoundDrawables method to do this. See the example here. I used this without using the setBounds and it worked. You can try either way.
UPDATE: Copying the code here incase the link goes down
Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
img.setBounds(0, 0, 60, 60);
txtVw.setCompoundDrawables(img, null, null, null);
or
Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
txtVw.setCompoundDrawablesWithIntrinsicBounds(img, null, null, null);
or
txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);
Simply you can try this also
txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);
Kotlin Version
Use below snippet to add a drawable left to the button:
val drawable = ContextCompat.getDrawable(context, R.drawable.ic_favorite_white_16dp)
button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)
Important Point in Using Android Vector Drawable
When you are using an android vector drawable and want to have backward compatibility for API below 21, add the following codes to:
In app level build.gradle:
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
In Application class:
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
}
}
myEdtiText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);
For me, it worked:
button.setCompoundDrawablesWithIntrinsicBounds(com.example.project1.R.drawable.ic_launcher, 0, 0, 0);
Worked for me. To set drawable at the right
tvBioLive.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close_red_400_24dp, 0)
If you are using drawableStart, drawableEnd, drawableTop or drawableBottom; you must use "setCompoundDrawablesRelativeWithIntrinsicBounds"
edittext.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.drawable.anim_search_to_close, 0)
I did this:
// Left, top, right, bottom drawables.
Drawable[] drawables = button.getCompoundDrawables();
// get left drawable.
Drawable leftCompoundDrawable = drawables[0];
// get new drawable.
Drawable img = getContext().getResources().getDrawable(R.drawable.ic_launcher);
// set image size (don't change the size values)
img.setBounds(leftCompoundDrawable.getBounds());
// set new drawable
button.setCompoundDrawables(img, null, null, null);
as #Jérémy Reynaud pointing out, as described in this answer, the safest way to set the left drawable without changing the values of the other drawables (top, right, and bottom) is by using the previous values from the button with setCompoundDrawablesWithIntrinsicBounds:
Drawable leftDrawable = getContext().getResources()
.getDrawable(R.drawable.yourdrawable);
// Or use ContextCompat
// Drawable leftDrawable = ContextCompat.getDrawable(getContext(),
// R.drawable.yourdrawable);
Drawable[] drawables = button.getCompoundDrawables();
button.setCompoundDrawablesWithIntrinsicBounds(leftDrawable,drawables[1],
drawables[2], drawables[3]);
So all your previous drawable will be preserved.
Might be helpful:
TextView location;
location=(TextView)view.findViewById(R.id.complain_location);
//in parameter (left,top,right,bottom) any where you wnat to put
location.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.arrow,0);
Add a Kotlin Extension
If you are going to be doing this frequently, adding an extension makes your code more readable. Button extends TextView; use Button if you want to be more narrow.
fun TextView.leftDrawable(#DrawableRes id: Int = 0) {
this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}
To use the extension, simply call
view.leftDrawable(R.drawable.my_drawable)
Anytime you need to clear, don't pass a param or make another extension called removeDrawables
Following is the way to change the color of the left icon in edit text and set it in left side.
Drawable img = getResources().getDrawable( R.drawable.user );
img.setBounds( 0, 0, 60, 60 );
mNameEditText.setCompoundDrawables(img,null, null, null);
int color = ContextCompat.getColor(this, R.color.blackColor);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
DrawableCompat.setTint(img, color);
} else {
img.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
Try this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
fillButton[i].setBackground(getBaseContext().getResources().getDrawable(R.drawable.drawable_name));
}
else {
fillButton[i].setBackgroundColor(Color.argb(255,193,234,203));
}
Try this:
((Button)btn).getCompoundDrawables()[0].setAlpha(btn.isEnabled() ? 255 : 100);

Categories