How to re-scale Bitmap image size? - android

Hi guys I am trying to load a image from a url and after loading that i am trying to re scale it such that it fits the whole screen after that the text and the buttons present are available below the image which are wrapped around using scroll view
this is my fragment
public class FirstFragment extends Fragment {
ImageView im;
Bitmap bitmap;
Drawable dr;
Bitmap bitap;
Bitmap newBitmap;
RelativeLayout rel;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.first_frag, container, false);
rel = (RelativeLayout) v.findViewById(R.id.relativla);
rel.setVisibility(View.INVISIBLE);
new LoadImage().execute("http://opinions.esy.es/bg.jpg");
Button b = (Button) v.findViewById(R.id.navi);
im = (ImageView) v.findViewById(R.id.imageView);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getContext(), Navi.class);
startActivity(i);
}
});
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
dr = new BitmapDrawable(getResources(),image);
bitap = ((BitmapDrawable) dr).getBitmap();
float scalingFactor = getBitmapScalingFactor(bitap);
Bitmap newBitmap = Util.ScaleBitmap(bitmap, scalingFactor);
im.setImageBitmap(newBitmap);
}else{
Toast.makeText(getContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
private float getBitmapScalingFactor(Bitmap bm) {
Toast.makeText(getContext(),"entered here",Toast.LENGTH_LONG).show();
// Get display width from device
int displayWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
// Get margin to use it for calculating to max width of the ImageView
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)this.im.getLayoutParams();
int leftMargin = layoutParams.leftMargin;
int rightMargin = layoutParams.rightMargin;
// Calculate the max width of the imageView
int imageViewWidth = displayWidth - (leftMargin + rightMargin);
rel.setVisibility(View.VISIBLE);
// Calculate scaling factor and return it
return ( (float) imageViewWidth / (float) bm.getWidth() );
}
}
My Util class
public class Util {
public static Bitmap ScaleBitmap(Bitmap bm, float scalingFactor) {
int scaleHeight = (int) (bm.getHeight() * scalingFactor);
int scaleWidth = (int) (bm.getWidth() * scalingFactor);
return Bitmap.createScaledBitmap(bm, scaleWidth, scaleHeight, true);
}
}
XML File
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
android:fillViewport="true"
>
<RelativeLayout
android:id="#+id/relativla"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/hamburger"
android:id="#+id/navi"
android:padding="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:id="#+id/imageView"
android:scaleType="fitCenter"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Diet Plans"
android:padding="10dp"
android:layout_marginTop="10dp"
android:textColor="#android:color/black"
android:textSize="25sp"
android:id="#+id/textView5"
android:layout_below="#+id/imageView"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/descrpitiondietplan"
android:textColor="#000000"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textSize="15sp"
android:padding="10dp"
android:id="#+id/textView6"
android:layout_below="#+id/textView5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Our Diet Plans"
android:textColor="#android:color/black"
android:padding="10dp"
android:textSize="25sp"
android:id="#+id/textView7"
android:layout_below="#+id/textView6"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView7"
android:layout_centerHorizontal="true"
android:padding="10dp">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Basic Diet Plan"
android:textColor="#android:color/white"
android:id="#+id/normmal"
android:background="#color/btn_login"
android:layout_marginBottom="10dp"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
It the toast insider the getBitmapScaling factor is called after the relative layout is viewed
Hope you guys can help me solve my issue

try add these
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(dm.widthPixels, dm.heightPixels);
im.setLayoutParams(params);
below im.setImageBitmap(newBitmap); onPostExecute

Related

How to implement multiple "Image add" layout?

I want to upload multiple images in my db. My question is how to design below screen to upload multiple images.
First: option to add 1st image:
After adding one image, Add option should move to right:
After adding 3 images, the add option should move to left side in 2nd row:
How to design the layout that will move on 2nd row after adding 3 images. Please help to design the above layout. Thank you in advance.
Check out this code.this is not same as u want but it will help u
layout xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.gennext.android.agrawalcars.UploadImage">
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scroll1"
android:layout_width="match_parent"
android:layout_above="#id/submit"
android:layout_alignParentTop="true"
android:layout_height="wrap_content"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:id="#+id/frameLayoutiv"
android:layout_width="match_parent"
android:layout_height="250dp"
android:visibility="gone">
<ImageView
android:id="#+id/imageprofile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#d2000000"
android:scaleType="fitCenter"
android:src="#drawable/cae3"
/>
</FrameLayout>
<GridLayout
android:id="#+id/lnrImages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:columnCount="3"
android:rowCount="3">
<android.support.v7.widget.CardView
android:id="#+id/addimage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_column="0"
android:layout_row="0"
app:cardElevation="5dp"
android:layout_margin="3dp"
android:textAllCaps="false"
app:cardBackgroundColor="#fff"
app:cardCornerRadius="2dp">
<ImageView
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="center"
android:layout_marginBottom="20dp"
android:src="#drawable/upload_photo"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:fontFamily="#font/noto_serif"
android:layout_marginTop="15dp"
android:text="Add\nCar Photos"
android:textSize="12sp"
/>
</android.support.v7.widget.CardView>
</GridLayout>
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/submit"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="18sp"
android:fontFamily="#font/noto_serif"
android:textStyle="bold"
android:textAllCaps="false"
android:theme="#style/buttonstylescont"
android:layout_alignParentBottom="true"
android:textColor="#color/actionbar_title_color"
android:text="Upload" />
</RelativeLayout>
Activity java file
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.Toast;
import com.vlk.multimager.activities.GalleryActivity;
import com.vlk.multimager.utils.Constants;
import com.vlk.multimager.utils.Image;
import com.vlk.multimager.utils.Params;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
public class UploadImage extends AppCompatActivity {
private String TAG = getClass().getName();
//views
private GridLayout lnrImages;
private CardView btnAddPhots, addinamge;
ImageView imageView1;
FrameLayout frameLayout;
int child;
//imageprocessing
Bitmap bitmap;
int height;
int width;
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
UploadImagesList uploadImagesList;
ArrayList<Image> images;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sellcar_uploadcarphotos);
//uploadimages
uploadImagesList = UploadImagesList.getInstance();
images = uploadImagesList.getImagesList();
// view find
lnrImages = findViewById(R.id.lnrImages);
child=lnrImages.getChildCount();
addinamge = findViewById(R.id.addimage);
imageView1 = findViewById(R.id.imageprofile);
frameLayout = findViewById(R.id.frameLayoutiv);
//get device height
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
height = displayMetrics.heightPixels;
width = displayMetrics.widthPixels;
param.height = width / 3;
param.width = width / 3;
param.rightMargin = 2;
param.topMargin = 2;
param.setGravity(Gravity.CENTER);
addinamge.setLayoutParams(param);
//add btn click
addinamge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadImage.this, GalleryActivity.class);
Params params = new Params();
params.setCaptureLimit(1);
params.setPickerLimit(1);
params.setToolbarColor(getResources().getColor(R.color.colorAccent));
params.setActionButtonColor(getResources().getColor(R.color.actionbarvtn));
params.setButtonTextColor(getResources().getColor(R.color.textcolor));
intent.putExtra(Constants.KEY_PARAMS, params);
startActivityForResult(intent, Constants.TYPE_MULTI_PICKER);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode != RESULT_OK) {
return;
}
if (intent != null) {
switch (requestCode) {
case Constants.TYPE_MULTI_CAPTURE:
ArrayList<Image> imagesList2 = intent.getParcelableArrayListExtra(Constants.KEY_BUNDLE_LIST);
//setImages(intent);
break;
case Constants.TYPE_MULTI_PICKER:
ArrayList<Image> imagesList = intent.getParcelableArrayListExtra(Constants.KEY_BUNDLE_LIST);
// images=uploadImagesList.getImagesList();
// images.addAll(imagesList);
// uploadImagesList.setImagesList(images);
// Log.d(TAG, "onActivityResult: pickerimages"+imagesList.size());
// Log.d(TAG, "onActivityResult: single imagelist"+uploadImagesList.getImagesList().size());
setImages(imagesList);
// if(uploadImagesList.getImagesList().size()<=8){
// }
//setImages(imagesList);
break;
}
} else {
Toast.makeText(this, "Image not selected", Toast.LENGTH_SHORT).show();
}
}
private void removeallviews() {
for(int i=1;i<lnrImages.getChildCount();i++){
lnrImages.removeViewAt(i);
}
}
private void setImages( ArrayList<Image> imagesList) {
Log.d(TAG, "setImages: single size"+imagesList.size());
Log.d(TAG, "setImages: check child count before delete it"+lnrImages.getChildCount());
if (lnrImages.getChildCount() <= 8) {
if (imagesList.size() != 0) {
Log.d(TAG, "setImages: afterremove child"+lnrImages.getChildCount());
for (int j = 0; j < imagesList.size(); j++) {
bitmap = decodeFile(imagesList.get(j).imagePath);
ImageView imageView = new ImageView(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = width / 3;
param.width = width / 3;
param.rightMargin = 2;
param.topMargin = 2;
param.setGravity(Gravity.CENTER);
imageView.setLayoutParams(param);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bitmap);
lnrImages.addView(imageView);
child=lnrImages.getChildCount();
Log.d(TAG, "setImages: childcount"+lnrImages.getChildCount());
for (int i = 1; i < lnrImages.getChildCount(); i++) {
final ImageView container = (ImageView) lnrImages.getChildAt(i);
container.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final Dialog dialog = new Dialog(UploadImage.this, android.R.style.Theme_Light);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().getAttributes().windowAnimations = R.style.Widget_AppCompat_ListPopupWindow;
dialog.getWindow().setBackgroundDrawableResource(R.color.dialogtransprant);
dialog.setContentView(R.layout.dialog_viewsingle_image);
dialog.findViewById(R.id.backarrow).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.deletebtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Todo : rearrange gridelayout after delete image.
lnrImages.removeViewInLayout(container);
dialog.dismiss();
}
});
dialog.findViewById(R.id.profilebtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
frameLayout.setVisibility(View.VISIBLE);
float screenWidth=getScreenWidth(UploadImage.this);
float newHeight = screenWidth;
if (bitmap.getWidth() != 0 && bitmap.getHeight() != 0) {
newHeight = (screenWidth * bitmap.getHeight()) / bitmap.getWidth();
}
imageView1.setImageBitmap(((BitmapDrawable) container.getDrawable()).getBitmap());
dialog.dismiss();
}
});
ImageView imageView2 = dialog.findViewById(R.id.imageiv);
imageView2.setImageBitmap(((BitmapDrawable) container.getDrawable()).getBitmap());
dialog.show();
}
});
}
}
} else {
Toast.makeText(this, "please select image", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "only 8 images are uploaded", Toast.LENGTH_SHORT).show();
}
}
/**
* getthis method from this url=https://stackoverflow.com/questions/2521959/how-to-scale-an-image-in-imageview-to-keep-the-aspect-ratio/6143521
* #param activity
* #return
*/
public static float getScreenWidth(Activity activity) {
Display display = activity.getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float pxWidth = outMetrics.widthPixels;
return pxWidth;
}
private Bitmap decodeFile(String imgPath) {
Bitmap b = null;
int max_size = 1000;
File f = new File(imgPath);
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > max_size || o.outWidth > max_size) {
scale = (int) Math.pow(2, (int) Math.ceil(Math.log(max_size / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (Exception e) {
Log.d(TAG, "decodeFile: " + e);
}
return b;
}
}
Layout
camera_lyout.xml
<?xml version="1.0" encoding="utf-8"?><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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:id="#+id/camera_shipment_fragment"
tools:context=".view.fragment.CameraShipmentFragment">
<HorizontalScrollView
android:layout_width="0dp"
android:layout_height="390dp"
android:layout_marginStart="1dp"
android:layout_marginEnd="1dp"
android:scrollbars="none"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:id="#+id/gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:textStyle="bold"
app:layout_editor_absoluteY="0dp"
app:layout_editor_absoluteX="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="Click below Icon to take Pictures and then click on Save Button to Scan Tag "
tools:ignore="MissingConstraints" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="110dp"
android:layout_height="100dp"
android:layout_marginTop="50dp"
app:srcCompat="#android:drawable/ic_menu_camera"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="75dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="QR CODE/BARCODE"
android:layout_marginTop="150dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<ImageView
android:id="#+id/imageView2"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginTop="50dp"
android:layout_marginLeft="150dp"
app:srcCompat="#drawable/add_button"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="75dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttonSave"
android:text="Save and Scan"
android:layout_marginTop="330dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
2nd Layout file (item_camera.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<ImageView
android:id="#+id/imageView"
android:layout_marginTop="175dp"
android:layout_width="130dp"
android:layout_height="130dp"
android:background="#drawable/img"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:textAlignment="center"
android:text="TextView" />
In Camera.java file start camera intent and on activity result write this code
LinearLayout gallery = getView().findViewById(R.id.gallery);
LayoutInflater inflater = LayoutInflater.from(getContext());
View view =inflater.inflate(R.layout.item_camera, gallery,false);
TextView textView =view.findViewById(R.id.textView);
textView.setText("Image" +value);
ImageView imageView =view.findViewById(R.id.imageView);
imageView.setImageBitmap(image);
gallery.addView(view);

how to set image URL as wallpaper (Glide Library)

please any help , i'm trying to set image as wallpaper i get this image by her url
i'm working with Glide Library i tried this code Set image as wallpaper from url but doesn't work for me please any help for resolve this issue?
file.java :
public class Pop extends Activity {
int width,height;
String url;
LinearLayout llsetwallpapers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop);
llsetwallpapers = (LinearLayout)findViewById(R.id.llSetWallpaper);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
this.width = dm.widthPixels;
this.height = dm.heightPixels;
getWindow().setLayout((int) (((double) this.width) * 0.9d), (int) (((double) this.height) * 0.75d));
getIntent().getSerializableExtra("WallpaperURL");
this.url = (String)getIntent().getSerializableExtra("WallpaperURL");
Glide.with(getApplicationContext()).load(this.url).into((ImageView)findViewById(R.id.imageSelectTo));
llsetwallpapers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// set as wallpapers
}
});
}
}
xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/linealL"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#65000000">
<ImageView
android:id="#+id/imageSelectTo"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<!-- Set as wallpaper button -->
<LinearLayout
android:id="#+id/llSetWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="10dp"
android:layout_marginStart="10dp"
android:background="#drawable/btn_rounded_corner"
android:gravity="center_vertical"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_alignParentLeft="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="#string/SetAsWallpaper"
android:textColor="#color/white"
android:textSize="18sp" />
</LinearLayout>
<!-- Download wallpaper button -->
<LinearLayout
android:id="#+id/llDownloadWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:background="#drawable/btn_rounded_corner"
android:gravity="center_vertical"
android:orientation="horizontal"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="#string/Download"
android:textColor="#color/white"
android:textSize="18sp" />
</LinearLayout>
private ImageView userImageView;
userImageView = (ImageView) findViewById(R.id.user_image);
Glide.with(getApplicationContext()).load(yourImageUrl).asBitmap()
.error(yourDefaultImageUrl or from R.id.drawableDefaultImage).centerCrop().into(userImageView);
Try this code it take a url converts it into bitmap and then set wallpaper according to screen size :
Declare variables
ImageView mImageView;
WallpaperManager wallpaperManager;
Bitmap bitmap1, bitmap2;
DisplayMetrics displayMetrics; //to find screen dimensions
int width, height; //to find screen dimensions
BitmapDrawable bitmapDrawable;
Button downloadButton;
String url="your wallpaper url";
Initialise your Views
mImageView = (ImageView) findViewById(R.id.imageView);
downloadButton= (Button) findViewById(R.id.Button);
In onCreate
Glide.with(this).load(spacePhoto.getUrl()).asBitmap().listener(new RequestListener<String, Bitmap>() {
#Override
public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {
mImageView.setImageBitmap(resource);
//Code to set bitmap as wallpaper according to screen size
fabOptions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
wallpaperManager = WallpaperManager.getInstance(getApplication());
bitmapDrawable = (BitmapDrawable) mImageView.getDrawable();
bitmap1 = bitmapDrawable.getBitmap();
GetScreenWidthHeight();
bitmap2 = Bitmap.createScaledBitmap(bitmap1, width, height, false);
wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
wallpaperManager.setBitmap(bitmap2);
wallpaperManager.suggestDesiredDimensions(width, height);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Snackbar snackbar = Snackbar
.make(v, "Wallpaper Set", Snackbar.LENGTH_SHORT);
snackbar.show();
}
});
return false;
}
}).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(mImageView);
Write this code outside of onCreate
public void GetScreenWidthHeight() {
displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
width = displayMetrics.widthPixels;
height = displayMetrics.heightPixels;
}

First image appearing small in size and on top left corner in a viewpager when rotate the device

Hi in my application i am using the Viewpager with PagerAdapter. it contains n number of images. but when i rotate the device when viewpager is on first image then the image shift to top left corner and appears very small. please have a look in the attached image.
code which i am using
public class CustomViewPager extends ViewPager {
private final long SWITCH_TIME_INTERVAL = 5000;
public CustomViewPager(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomViewPager(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
postDelayed(mSwither, SWITCH_TIME_INTERVAL);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height)
height = h;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
/**
* this Runnable is use for automatically switching the view pager item.
* #author
*/
private Runnable mSwither = new Runnable() {
#Override
public void run() {
if( CustomViewPager.this.getAdapter() != null )
{
int count = CustomViewPager.this.getCurrentItem();
if( count == (CustomViewPager.this.getAdapter().getCount() - 1) )
{
count = 0;
}else
{
count++;
}
//Log.d(this.getClass().getName(), "Curent Page " + count + "");
CustomViewPager.this.setCurrentItem(count, true);
}
CustomViewPager.this.postDelayed(this, SWITCH_TIME_INTERVAL);
}
};
#Override
public boolean onTouchEvent(MotionEvent arg0) {
switch (arg0.getAction()) {
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP :
postDelayed(mSwither, SWITCH_TIME_INTERVAL);
break;
default:
removeCallbacks(mSwither);
break;
}
return super.onTouchEvent(arg0);
} }
//PagerAdapter onInstantiateItem code..
#Override
public Object instantiateItem(ViewGroup container, final int position) {
mImageFetcher.setLoadingImage(R.drawable.placeholder_tabportrait);
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.test_fragment1, container, false);
description = (TextView) itemView.findViewById(R.id.description);
title = (TextView) itemView.findViewById(R.id.car_title);
published = (TextView) itemView.findViewById(R.id.date_data);
author = (TextView) itemView.findViewById(R.id.author);
jumbo_tron_image = (ImageView) itemView.findViewById(R.id.jumbo_imgae);
TrayItem trayItem = getData(position);
if (null != trayItem) {
if (trayItem.getType() != null) {
if (trayItem.getImages() != null) {
mImageFetcher.loadImage(trayItem.getImages().getWidget(),
jumbo_tron_image);
}
return itemView;
}
//xml code.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="500dp"
android:background="#color/white">
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical"
>
<ImageView
android:id="#+id/jumbo_imgae"
android:layout_width="match_parent"
android:scaleType="fitXY"
android:layout_height="300dp"
/>
</FrameLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="#dimen/container_height"
android:layout_below="#+id/main_container">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
android:id="#+id/linearLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_alignParentLeft="true"
android:textStyle="bold"
android:layout_weight="0.5"
android:textColor="#color/black"
android:id="#+id/car_title"
android:maxLines="2"
android:ellipsize="end"
android:textSize="20sp"
android:text=" "/>
<ImageView
android:id="#+id/iv_add_test1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:paddingTop="10dp"
android:src="#drawable/add_icon"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/car_title"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout2"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/linearLayout3"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:id="#+id/date_data"
android:layout_width="90dp"
android:layout_height="18dp"
android:text=""
android:textSize="13sp"
android:layout_gravity="left"
android:gravity="center"
android:textColor="#color/white"
android:background="#drawable/date_bg"/>
<TextView
android:id="#+id/author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="15sp"
android:layout_marginLeft="10dp"
android:textColor="#color/black"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout> </RelativeLayout>

Android expand and contract animation on Layout

I have a normal Relative Layout with text view and progress bar.
Now, since i have a fixed width and height of the layout the text is properly placed in the center and looks good, onclick of layout we are changing the visibility of progress bar to "Visible", but since i have a fixed width the progress bar is on top of the text.
What i am trying to achieve is , onclick increase the right end width of the layout along with animation.
Here is my code :
<RelativeLayout
android:id="#+id/rellyt"
android:layout_width="150dp"
android:layout_height="35dp"
android:layout_margin="5dp"
android:background="#B7E4FF"
android:clickable="true" >
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:text="click on this button"
android:textColor="#000000"
android:textSize="14sp" />
<ProgressBar
android:id="#+id/prgbar"
style="#android:style/Widget.ProgressBar.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="8dp"
android:visibility="visible" />
</RelativeLayout>
Screen shot of the layout :
Animation
public class ResizeWidthAnimation extends Animation
{
private int mWidth;
private int mStartWidth;
private View mView;
public ResizeWidthAnimation(View view, int width)
{
mView = view;
mWidth = width;
mStartWidth = view.getWidth();
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t)
{
int newWidth = mStartWidth + (int) ((mWidth - mStartWidth) * interpolatedTime);
mView.getLayoutParams().width = newWidth;
mView.requestLayout();
}
#Override
public void initialize(int width, int height, int parentWidth, int parentHeight)
{
super.initialize(width, height, parentWidth, parentHeight);
}
#Override
public boolean willChangeBounds()
{
return true;
}
}
Usage
if(animate)
{
ResizeWidthAnimation anim = new ResizeWidthAnimation(leftFrame, leftFragmentWidthPx);
anim.setDuration(500);
leftFrame.startAnimation(anim);
}
else
{
this.leftFragmentWidthPx = leftFragmentWidthPx;
LayoutParams lp = (LayoutParams) leftFrame.getLayoutParams();
lp.width = leftFragmentWidthPx;
leftFrame.setLayoutParams(lp);
}
Try this way,hope this will help you to solve your problem.
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<LinearLayout
android:id="#+id/customLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#B7E4FF"
android:gravity="center"
android:padding="5dp">
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click on this button"
android:textColor="#000000"
android:textSize="14sp" />
<ProgressBar
android:id="#+id/prgbar"
style="#android:style/Widget.ProgressBar.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:visibility="invisible" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private LinearLayout customLayout;
private ProgressBar prgbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
customLayout = (LinearLayout) findViewById(R.id.customLayout);
prgbar = (ProgressBar) findViewById(R.id.prgbar);
customLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(prgbar.getVisibility() == View.INVISIBLE){
prgbar.setVisibility(View.VISIBLE);
}else{
prgbar.setVisibility(View.INVISIBLE);
}
}
});
}
}

Android - multiple draw on ImageView

I'm new in Android and I have a problem with my app: I have a layout with an ImageView and more EditTexts and Buttons. I'm trying to draw a circle on the Image View every time I input coordinates in a EditText and push a button.
I found a way to make it work the first time, but if I just copy the same code for the 2nd button it draws the new circle and erases the first one. And I want to have both of them...
Somebody can tell me whet I do wrong? Thanks a lot.
My activity:
public class IndoorPositioningMainActivity extends Activity {
Button InitialPos = null;
Button P1 = null;
EditText InitialPosX = null;
EditText InitialPosY = null;
EditText InitialPosZ = null;
EditText P1X = null;
EditText P1Y = null;
EditText P1Z = null;
ImageView Image = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_indoor_positioning_main);
InitialPos = (Button)findViewById(R.id.ButtonInitialPosInput);
P1 = (Button)findViewById(R.id.ButtonP1);
InitialPosX = (EditText)findViewById(R.id.InitialPosInputX);
InitialPosY = (EditText)findViewById(R.id.InitialPosInputY);
InitialPosZ = (EditText)findViewById(R.id.InitialPosInputZ);
P1X = (EditText)findViewById(R.id.P1InputX);
P1Y = (EditText)findViewById(R.id.P1InputY);
P1Z = (EditText)findViewById(R.id.P1InputZ);
Image = (ImageView)findViewById(R.id.imageView1);
InitialPos.setOnClickListener(InitialPosListener);
P1.setOnClickListener(P1Listener);
InitialPosX.addTextChangedListener(textWatcher);
InitialPosY.addTextChangedListener(textWatcher);
InitialPosZ.addTextChangedListener(textWatcher);
P1X.addTextChangedListener(textWatcher);
P1Y.addTextChangedListener(textWatcher);
P1Z.addTextChangedListener(textWatcher);
new PositionAsync().execute();
}
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
};
private OnClickListener InitialPosListener = new OnClickListener() {
#Override
public void onClick(View v) {
String x = InitialPosX.getText().toString();
String z = InitialPosZ.getText().toString();
float x0 = Float.valueOf(x);
float z0 = Float.valueOf(z);
BitmapFactory.Options myOptions = new BitmapFactory.Options();
myOptions.inDither = true;
myOptions.inScaled = false;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.est,myOptions);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.RED);
Bitmap workingBitmap = Bitmap.createBitmap(bitmap);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawCircle(x0, z0, 50, paint);
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(mutableBitmap);
}
};
private OnClickListener P1Listener = new OnClickListener() {
#Override
public void onClick(View v) {
String x11 = P1X.getText().toString();
String z11 = P1Z.getText().toString();
float x1 = Float.valueOf(x11);
float z1 = Float.valueOf(z11);
BitmapFactory.Options myOptions = new BitmapFactory.Options();
myOptions.inDither = true;
myOptions.inScaled = false;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.est,myOptions);
Paint paint1 = new Paint();
paint1.setAntiAlias(true);
paint1.setColor(Color.BLUE);
Bitmap workingBitmap = Bitmap.createBitmap(bitmap);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawCircle(x1, z1, 25, paint1);
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(mutableBitmap);
}
};
//XML READER
class PositionAsync extends AsyncTask<Void, Void, Void> {
XMLHelper helper;
#Override
protected Void doInBackground(Void... arg0) {
helper = new XMLHelper();
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
my xml layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="10px" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="70"
android:adjustViewBounds="true"
android:cropToPadding="false"
android:scaleType="centerInside"
android:src="#drawable/est" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
android:layout_weight="30"
android:orientation="vertical"
android:padding="10px" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/InitialPosX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" />
<EditText
android:id="#+id/InitialPosInputX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/InitialPosY"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Y" />
<EditText
android:id="#+id/InitialPosInputY"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/InitialPosZ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Z" />
<EditText
android:id="#+id/InitialPosInputZ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
<Button
android:id="#+id/ButtonInitialPosInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/P1X"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" />
<EditText
android:id="#+id/P1InputX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/P1Y"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Y" />
<EditText
android:id="#+id/P1InputY"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/P1Z"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Z" />
<EditText
android:id="#+id/P1InputZ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
<Button
android:id="#+id/ButtonP1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
</LinearLayout>
Firstly I suppose that "#drawable/est" is the basic image that will be painted. Then Every time that the button is clicked "est" image is reopened so the previous circles aren't saved.
One possible solution is to use a SurfaceView. There are many tutorials on internet about it.
Other solution is not to load "est" image every time, instead of that try saving the canvas and draw the circles one after another.
Hope it helps
The problem is that you only draw 1 circle in your OnClickListener(), and you draw it on a bitmap that you read from a file every time.
Instead you should save the coordinates into a list, and in the click listener draw all the circles from the list.
Like this:
String x11 = P1X.getText().toString();
String z11 = P1Z.getText().toString();
float x1 = Float.valueOf(x11);
float z1 = Float.valueOf(z11);
points.add(new Point(x1, z1));
And then:
for (Point point : points) {
canvas.drawCircle(point.x, point.y, 25, paint1);
}

Categories

Resources