Android set image as wallpaper - android

Please show me an example code on how to set image as wallpaper using Android WallpaperManager. I have shortened and edited my question. Hopefully you guys could understand my question. I will show some attempts I have made.
HomeActivity.class
public class HomeActivity extends BaseActivity {
String[] imageUrls;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_home);
ArrayList<String> url = new ArrayList<String>();
try {
URL url_link = new URL("http://mywebsite.net/web/thumb.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url_link.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("list");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element)node;
NodeList nameList = fstElmnt.getElementsByTagName("thumb_url");
Element nameElement = (Element)nameList.item(0);
nameList = nameElement.getChildNodes();
url.add(nameList.item(0).getNodeValue());
}
imageUrls = (String[]) url.toArray(new String[0]);
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
public void onImageGridClick(View view) {
Intent intent = new Intent(this, ImageGridActivity.class);
intent.putExtra(Extra.IMAGES, imageUrls);
startActivity(intent);
}
public void onImagePagerClick(View view) {
Intent intent = new Intent(this, ImagePagerActivity.class);
intent.putExtra(Extra.IMAGES, imageUrls);
startActivity(intent);
}
}
ImagePagerActivity.class
package com.nostra13.example.universalimageloader;
import java.io.IOException;
import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
private DisplayImageOptions options;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheOnDisc()
.imageScaleType(ImageScaleType.EXACT)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls));
pager.setCurrentItem(pagerPosition);
}
public void setWallpaper() {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.id.pager); // nothing happened
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_clear_memory_cache:
imageLoader.clearMemoryCache();
return true;
case R.id.item_clear_disc_cache:
setWallpaper();
return true;
default:
return false;
}
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public void finishUpdate(View container) {
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object instantiateItem(View view, int position) {
final View imageLayout = inflater.inflate(R.layout.item_pager_image, null);
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
public void onLoadingFailed(FailReason failReason) {
String message = null;
switch (failReason) {
case IO_ERROR:
message = "Input/Output error";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
public void onLoadingComplete(Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
public void onLoadingCancelled() {
// Do nothing
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
}
1st Attempt (My pagerPosition is giving error "pagerPosition cannot be resolved to a variable")
public void setWallpaper(){
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), pagerPosition);
try {
ImagePagerActivity.this.setWallpaper(bitmap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Gallery Example", "Image setted.");
}
2nd Attempt (My pagerPosition is giving error "pagerPosition cannot be resolved to a variable")
public void setWallpaper() {
try {
File file = new File("/sdcard/sampleimage");
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), pagerPosition);
bitmap.compress(CompressFormat.JPEG, 80, new FileOutputStream(file));
Context context = this.getBaseContext();
context.setWallpaper(bitmap);
Toast.makeText(getApplicationContext(), "Wallpaper has been set", Toast.LENGTH_SHORT).show();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.set_wallpaper:
setWallpaper();
return true;
default:
return false;
}
}
3rd Attempt (My setResource(R.id.pager) is not getting the image from the viewpager.
public void setWallpaper() {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.id.pager);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Conclusion
If i put the below codes above my onCreate my whole project will not run.
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
final int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);

Try below code in ImagePagerActivity, i tested below code and it is working.
// fetch bitmap from view
public static Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view
.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
// if we unable to get background drawable then we will set white color as wallpaper
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
public void setWall(int i) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
// below line of code will set your current visible pager item to wallpaper
// first we have to fetch bitmap from visible view and then we can pass it to wallpaper
myWallpaperManager.setBitmap(getBitmapFromView(pager.getChildAt(1)));
// below line of code will set input stream data directly to wallpaper
// myWallpaperManager.setStream(InputStream Data);
// below line of code will set any image which is in the drawable folder
// myWallpaperManager.setResource(R.drawable.icon);
} catch (IOException e) {
e.printStackTrace();
}
}
It will set current visible pager's item view(if it is progress wheel or image).

This might help you with your setbackground method...
String imagePath = ""; // YOUR PATH HERE
FileInputStream is = new FileInputStream(new File(imagePath));
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap b = BitmapFactory.decodeStream(bis);
Bitmap bitmapToUse = Bitmap.createScaledBitmap(b, parent.getWidth(), parent.getHeight(), true);
b.recycle();
if(!("").equals(imagePath)){
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
Drawable wallpaperDrawable = wallpaperManager.getDrawable();
wallpaperManager.setBitmap(bitmapToUse);
}
That should set your file to your wallpaper no problem.
Can you be more specific on what you need for the "saveImage()"? Where are you trying to save from? Is it local storage? Or a website? More details please.
[Edit]
Updated code for clarity
[Edit 2]
To save images from a URL...
File imageFile = new File("image.png"); // This is location AND file name, all i put here was the filename
URL url = new URL("http://www.whatever.com/image.png");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
FileOutputStream out = new FileOutputStream(imageFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
[Edit 3]
The 'parent' is either your parent view (generally the view for the current activity). There are other ways to set this, the parent.width/height is how you're going to define how large the wallpaper image needs to be.

Related

get Data to Fragment from Activity

I want to get data from activity but I keep getting error this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference.
TrafficActivity.class (Activity)
public class TrafficActivity extends AppCompatActivity {
public static final String FRAGMENT_PDF_RENDERER_BASIC = "pdf_renderer_basic";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_traffic);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_traffic);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(TrafficActivity.this, IpuclariSayfasi.class));
}
});
if (savedInstanceState == null)
{
getFragmentManager().beginTransaction()
.add(R.id.container, new PdfRendererBasicFragment(), FRAGMENT_PDF_RENDERER_BASIC)
.commit();
}
}}
PdfRendererBasicFragment.class(Fragment)
public class PdfRendererBasicFragment extends Fragment implements
View.OnClickListener
{
private static final String O_ANKI_SAYFA_DURUMU = "guncel_sayfa_index";
private ParcelFileDescriptor mFileDescriptor;
private PdfRenderer mPdfRenderer;
private PdfRenderer.Page mGuncelSayfa;
private ImageView mImageView;
private ImageButton mOncekiButon;
private ImageButton mSonrakiButon;
public static String FILENAME;
public PdfRendererBasicFragment()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_pdf_renderer_basic, container, false);
}
#Override
public void onClick(View view)
{
switch (view.getId()) {
case R.id.onceki: {
//onceki sayfaya geç
showPage(mGuncelSayfa.getIndex() - 1);
break;
}
case R.id.sonraki: {
// sonraki sayfaya geç
showPage(mGuncelSayfa.getIndex() + 1);
break;
}
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mImageView = (ImageView) view.findViewById(R.id.pdf_goruntusu);
mOncekiButon = (ImageButton) view.findViewById(R.id.onceki);
mSonrakiButon = (ImageButton) view.findViewById(R.id.sonraki);
mOncekiButon.setOnClickListener(this);
mSonrakiButon.setOnClickListener(this);
int index = 0;
if (null != savedInstanceState) {
index = savedInstanceState.getInt(O_ANKI_SAYFA_DURUMU, 0);
}
showPage(index);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
openRenderer(activity);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(activity, "Beklenmedik hata: " + e.getMessage(), Toast.LENGTH_SHORT).show();
activity.finish();
}
}
#Override
public void onDetach() {
try {
closeRenderer();
} catch (IOException e) {
e.printStackTrace();
}
super.onDetach();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mGuncelSayfa) {
outState.putInt(O_ANKI_SAYFA_DURUMU, mGuncelSayfa.getIndex());
}
}
private void openRenderer(Context context) throws IOException
{
// bu ornekte, asset klasöründeki PDF'i okuyoruz.
FILENAME= getArguments().getString("file_name");
File file = new File(context.getCacheDir(), FILENAME);
if (!file.exists())
{
InputStream asset = context.getAssets().open(FILENAME);
FileOutputStream output = new FileOutputStream(file);
final byte[] buffer = new byte[1024];
int size;
while ((size = asset.read(buffer)) != -1) {
output.write(buffer, 0, size);
}
asset.close();
output.close();
}
mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
mPdfRenderer = new PdfRenderer(mFileDescriptor);
}
private void closeRenderer() throws IOException {
if (null != mGuncelSayfa) {
mGuncelSayfa.close();
}
mPdfRenderer.close();
mFileDescriptor.close();
}
private void showPage(int index) {
if (mPdfRenderer.getPageCount() <= index) {
return;
}
if (null != mGuncelSayfa) {
mGuncelSayfa.close();
}
mGuncelSayfa = mPdfRenderer.openPage(index);
// ÖNEMLİ: Hedef bitmap ARGB olmalı, RGB olmamalı.
Bitmap bitmap = Bitmap.createBitmap(mGuncelSayfa.getWidth(), mGuncelSayfa.getHeight(),
Bitmap.Config.ARGB_8888);
mGuncelSayfa.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
mImageView.setImageBitmap(bitmap);
sayfayıGuncelle();
}
private void sayfayıGuncelle() {
int index = mGuncelSayfa.getIndex();
int pageCount = mPdfRenderer.getPageCount();
mOncekiButon.setEnabled(0 != index);
mSonrakiButon.setEnabled(index + 1 < pageCount);
getActivity().setTitle(getString(R.string.app_name_with_index, index + 1, pageCount));
}
public int sayfaSayisiniGetir()
{
return mPdfRenderer.getPageCount();
}
You are setting the argument on the Fragment but calling the Activity
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("file_name", "sample3.pdf");
PdfRendererBasicFragment ff=new PdfRendererBasicFragment();
ff.setArguments(bundle);
startActivity(new Intent(IpuclariSayfasi.this,TrafficActivity.class));
}
And when you really commit the Fragment, you creating a new instance, without any argument:
if (savedInstanceState == null)
{
getFragmentManager().beginTransaction()
.add(R.id.container, new PdfRendererBasicFragment(), FRAGMENT_PDF_RENDERER_BASIC)
.commit();
}
Make the first implementation on the real Fragment call, like this:
if (savedInstanceState == null) {
Bundle bundle = new Bundle();
bundle.putString("file_name", "sample3.pdf");
PdfRendererBasicFragment ff=new PdfRendererBasicFragment();
ff.setArguments(bundle);
getFragmentManager().beginTransaction()
.add(R.id.container, ff, FRAGMENT_PDF_RENDERER_BASIC)
.commit();
}
You have the problem here
FILENAME= getArguments().getString("file_name");
getArguments() is null since you are setting arguments for
PdfRendererBasicFragment ff=new PdfRendererBasicFragment();
ff.setArguments(bundle);
but then you're creating a new Fragment in TrafficActivity.class
.add(R.id.container, new PdfRendererBasicFragment(), FRAGMENT_PDF_RENDERER_BASIC)
and this is the one you're using, but this one does not have any arguments in it

Pass Image (from Json) in gridView to new Activity

I have a gridView in my app containing images. Images are loaded from json over the web. I want that when a user click on any image in the gridView a new activity will open container the image clicked by the user. The images are loaded from links defined in json. I tried but didn't get desired result.
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import com.dragedy.dream.adapter.MyArrayAdapter;
import com.dragedy.dream.model.MyDataModel;
import com.dragedy.dream.parser.JSONParser;
import com.dragedy.dream.utils.InternetConnection;
import com.dragedy.dream.utils.Keys;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class memechoose extends AppCompatActivity {
private GridView gridView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memechoose);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/**
* Array List for Binding Data from JSON to this List
*/
list = new ArrayList<>();
/**
* Binding that List to Adapter
*/
adapter = new MyArrayAdapter(this, list);
/**
* Getting List and Setting List Adapter
*/
gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i= new Intent(memechoose.this, MemeEditorActivity.class);
i.putExtra("image_path", list.get(position).getImage());
startActivity(i);
}
});
/**
* Just to know onClick and Printing Hello Toast in Center.
*/
if (InternetConnection.checkConnection(getApplicationContext())) {
new GetDataTask().execute();
}
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
/**
* Progress Dialog for User Interaction
*/
dialog = new ProgressDialog(memechoose.this);
dialog.setTitle("Hey Wait Please...");
dialog.setMessage("I am getting your JSON");
dialog.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
/**
* Getting JSON Object from Web Using okHttp
*/
JSONObject jsonObject = JSONParser.getDataFromWeb();
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "contacts" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_MEME);
/**
* Check Length of Array...
*/
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
/**
* Creating Every time New Object
* and
* Adding into List
*/
MyDataModel model = new MyDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
String image = innerObject.getString(Keys.KEY_MEME_PIC);
/**
* Getting Object from Object "phone"
*/
model.setImage(image);
/**
* Adding name and phone concatenation in List...
*/
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
/**
* Checking if List size if more than zero then
* Update ListView
*/
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} //else {
// Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
// }
}
}
}
and the activity in which i want to display the images is as follows:
public class MemeEditorActivity extends AppCompatActivity {
private Toolbar toolbar;
private MemeEditorActivity selfRef;
private SharedPreferences setting;
private LinearLayout linlaHeaderProgress;
private float memeEditorLayoutWidth;
private float memeEditorLayoutHeight;
private LinearLayout tutorial;
private LinearLayout memeEditorLayout;
private MemeEditorView memeEditorView;
private ImageView forwardButtonImageView;
private Bitmap memeBitmap;
private File cacheImage_forPassing;
private File myDir;
private String dataDir;
private boolean firsttimes;
private boolean tutorialPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meme_editor);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
selfRef = this;
// Transparent bar on android 4.4 or above
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT)
{
Window window = getWindow();
// Translucent status bar
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// Translucent navigation bar
window.setFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
// Initialize progress bar
linlaHeaderProgress = (LinearLayout)findViewById(R.id.linlaHeaderProgress);
linlaHeaderProgress.bringToFront();
// Initialize tutorial
setting = PreferenceManager
.getDefaultSharedPreferences(MemeEditorActivity.this);
SharedPreferences prefre = getSharedPreferences("Meme_Pref", Context.MODE_PRIVATE);
firsttimes = prefre.getBoolean("Meme_Pref", true);
tutorialPreference = setting.getBoolean("Tutor_Preference", false);
SharedPreferences.Editor firstTimeEditor = prefre.edit();
// See if tutorial is needed to be shown
tutorial = (LinearLayout)findViewById(R.id.meme_editor_tutorial);
tutorial.setEnabled(false);
tutorial.setOnClickListener(new View.OnClickListener()
{
# Override
public void onClick(View view)
{
tutorial.setVisibility(View.GONE);
tutorial.setEnabled(false);
}
});
if(firsttimes)
{
tutorial.setVisibility(View.VISIBLE);
tutorial.bringToFront();
tutorial.setEnabled(true);
firstTimeEditor.putBoolean("Meme_Pref", false);
firstTimeEditor.commit();
}
else if(tutorialPreference)
{
tutorial.setVisibility(View.VISIBLE);
tutorial.bringToFront();
tutorial.setEnabled(true);
tutorialPreference = setting.getBoolean("Tutor_Preference", false);
}
else
{
tutorial.setVisibility(View.GONE);
tutorial.setEnabled(false);
}
// Get the data directory for the app
PackageManager m = getPackageManager();
dataDir = getPackageName();
try
{
PackageInfo p = m.getPackageInfo(dataDir, 0);
dataDir = p.applicationInfo.dataDir;
myDir = new File(dataDir+"/cache");
if(!myDir.exists())
myDir.mkdirs();
if(myDir.setWritable(true))
Log.i("meme", "myDir is writable");
else
Log.i("meme", "myDir is not writable");
}catch(PackageManager.NameNotFoundException e)
{
Log.w("yourtag", "Error Package name not found ", e);
}
// Get the intent and get the image path to be the meme image
Intent shareIntent = getIntent();
String imagePath = shareIntent.getStringExtra("image_path");
// Create the SandboxView
setting = PreferenceManager
.getDefaultSharedPreferences(MemeEditorActivity.this);
// final int memeSize = Integer.valueOf(setting.getString("image_size","720"));
final int memeSize = setting.getInt("image_size", 720);
Log.i("meme", "memeSize = "+memeSize);
memeEditorLayout = (LinearLayout)findViewById(R.id.memeEditorLayout);
memeEditorLayout.setGravity(Gravity.CENTER);
try
{
Log.i("imagePath", imagePath);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
memeEditorView = new MemeEditorView(this, bitmap);
memeEditorView.setLayoutParams(new ViewGroup.LayoutParams(memeSize, memeSize));
// Scale the sand box and add it into the layout
ViewTreeObserver viewTreeObserver = memeEditorLayout
.getViewTreeObserver();
// For getting the width and height of a dynamic layout during
// onCreate
viewTreeObserver
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
# Override
public void onGlobalLayout()
{
memeEditorLayout.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
memeEditorLayoutWidth = memeEditorLayout.getHeight();
memeEditorLayoutHeight = memeEditorLayout.getWidth();
float scalingFactor = memeEditorLayoutWidth/(float)memeSize;
Log.i("memeEditorLayoutWidth", Float.toString(memeEditorLayoutWidth));
Log.i("ScaleFactor", Float.toString(scalingFactor));
memeEditorView.setScaleX(scalingFactor);
memeEditorView.setScaleY(scalingFactor);
}
});
memeEditorLayout.addView(memeEditorView);
// Set save button on click method
forwardButtonImageView = (ImageView)findViewById(R.id.forwardButtonImage);
forwardButtonImageView.setOnClickListener(new View.OnClickListener()
{
# Override
public void onClick(View arg0)
{
forwardButtonImageView.setEnabled(false);
Forward forward = new Forward();
forward.execute();
}
});
}catch(OutOfMemoryError e)
{
Toast.makeText(selfRef, "Your device is out of memory.", Toast.LENGTH_LONG).show();
finish();
}catch(Exception e)
{
Log.i("Meme Editor Activity", e.toString());
Toast.makeText(selfRef, "Ops, something went wrong.", Toast.LENGTH_LONG).show();
finish();
}
}
// Delete a files
private void deleteFile(File file)
{
if(file!=null)
{
Log.i("deleteFile", file.toString()+((file.exists())?" is Exist.":"is not exist!!!!"));
// Check if the file exist
if(file.exists())
// Clear the file inside if it is a directory
if(file.isDirectory())
{
String[] children = file.list();
for(int i = 0;i<children.length;i++)
{
File f = new File(file, children[i]);
if(f.delete())
Log.i("deleteFile", f.getAbsolutePath()+" is deleted....");
else
Log.i("deleteFile", f.getAbsolutePath()+" is not deleted!!!!");
}
}
}
}
# Override
protected void onPause()
{
// Hide the progress bar
linlaHeaderProgress.setVisibility(View.GONE);
forwardButtonImageView.setEnabled(true);
super.onPause();
}
# Override
protected void onResume()
{
super.onResume();
memeEditorView.setEnabled(true);
memeEditorView.resume();
}
# Override
protected void onDestroy()
{
// Try to delete cache if possible
// deleteFile(myDir);
// bp_release();
//memeEditorView.destroyDrawingCache();
super.onDestroy();
}
# Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.meme_editor, menu);
return true;
}
# Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch(item.getItemId())
{
case R.id.reset_sandbox:
memeEditorView.reset();
return true;
case R.id.action_settings:
Intent intent = new Intent(selfRef, MainActivity.class);
startActivity(intent);
return true;
case android.R.id.home:
// When the action bar icon on the top right is clicked, finish this
// activity
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// save image to a specific places
private void saveImage()
{
// Create the file path and file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fname = timeStamp+".png";
cacheImage_forPassing = new File(myDir, fname);
// Remove duplicates
if(cacheImage_forPassing.exists())
cacheImage_forPassing.delete();
// Try save the bitmap
try
{
FileOutputStream out = new FileOutputStream(cacheImage_forPassing);
memeBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Log.i("memeCacheLocation", cacheImage_forPassing.toString());
}catch(Exception e)
{
e.printStackTrace();
}
}
// Async task for onClick
class Forward extends AsyncTask<Object,Object,Object>
{
// Before forwarding
# Override
protected void onPreExecute()
{
super.onPreExecute();
linlaHeaderProgress.setVisibility(View.VISIBLE);
linlaHeaderProgress.bringToFront();
memeEditorView.pause();
memeEditorView.invalidate();
}
// Forwarding
# Override
protected String doInBackground(Object ... arg0)
{
Intent forward = new Intent(selfRef, MainActivity.class);
memeEditorView.setDrawingCacheEnabled(true);
memeEditorView.buildDrawingCache();
memeBitmap = Bitmap.createBitmap(memeEditorView.getDrawingCache());
saveImage();
forward.putExtra("cs4295.memcreator.memeImageCache",
cacheImage_forPassing.getPath());
startActivity(forward);
memeEditorView.setDrawingCacheEnabled(false);
return "DONE";
}
// After forwarding
# Override
protected void onPostExecute(Object result)
{
linlaHeaderProgress.setVisibility(View.GONE);
super.onPostExecute(result);
}
}
// Clear the Bitmap from memory
private void bp_release()
{
if(memeBitmap!=null&&!memeBitmap.isRecycled())
{
memeBitmap.recycle();
memeBitmap = null;
}
}
}
#AC-OpenSource E/BitmapFactory: Unable to decode stream:
java.io.FileNotFoundException:
/http:/static2.businessinsider.com/image/56e3189152bcd0320c8‌​b5cf7-480/sammy-grin‌​er-success-kid-meme.‌​jpg:
open failed: ENOENT (No such file or directory)
You have a slash before http

StateListDrawable drawables from URL

I'm trying to make a button with StateListDrawable but with 2 remote images.
I'm trying like this :
package com.mylisabox.common.helpers;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.AsyncTask;
import java.io.InputStream;
import java.net.URL;
/**
* Created by jaumard on 16/10/2015.
*/
public class RemoteStateListDrawable extends StateListDrawable
{
Drawable drawableOn;
Drawable drawableOff;
public RemoteStateListDrawable(String urlOn, String urlOff)
{
loadImageAsDrawable(urlOff, false);
loadImageAsDrawable(urlOn, true);
}
#Override
protected boolean onStateChange(int[] stateSet)
{
return super.onStateChange(stateSet);
}
#Override
public boolean isStateful()
{
return true;
}
public void loadImageAsDrawable(final String url, final boolean isOnState)
{
new AsyncTask<Void, Void, Drawable>()
{
#Override
protected Drawable doInBackground(Void... params)
{
try
{
// open the stream
InputStream is = new URL(url).openStream();
String imageName = "src";
Drawable draw = Drawable.createFromStream(is, imageName);
return draw;
}
catch (Exception e)
{
// something went wrong
return null;
}
}
#Override
protected void onPostExecute(Drawable drawable)
{
super.onPostExecute(drawable);
if (isOnState)
{
drawableOn = drawable;
addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_selected}, drawableOn);
}
else
{
drawableOff = drawable;
addState(new int[]{}, drawableOff);
}
}
}.execute();
}
}
But it's not working... The off image was show but never the on image if I click on the button.
android.R.attr.state_pressed, android.R.attr.state_selected is mean pressed and selected , remove selected and try again
2.try to exchange the off and on drawable
3.try to use diffenent imageName
String imageName = "src";

How to check (listen) asynctask status when starting activity

I have an Activity 'A' with it's child fragment, Activity 'B' and GetTask class.
User launches the application and gets to Activity A. While user looks at ListView, AsyncTask is loading data for Activity B. But it may take a while and user can move to Activity B with no data for a ListView yet. So he have to wait. I'm creating a ProgressDialog here and want to check somehow when AsyncTask is completed.
Now I use static variable instance with a static method getInstance() which set to '1' in PostExecute method and then I take it in my Activity B
int instance = GetTask.getInstance();
Then I create a ProgressDialog, but I can't get AsyncTask status to know when dismiss my dialog. task.getStatus() always show RUNNING status.
I tried to make it with OnComplete listener, sample code below
public class GetForeignToursTask extends AsyncTask implements OnTaskCompleteListener {
ActivityA just launches an AsyncTask:
GetTask task = new GetTask(this, null);
task.execute(url);
GetTask class sample:
private Context context;
OnTaskCompleteListener listener;
private static int instance = 0;
public GetTask(Context context, OnTaskCompleteListener listener) {
this.listener = listener;
this.context = context;
}
#Override
public void onTaskCompleted(int status) {
Log.d("log", status); // I don't get here at all
}
ActivityB code:
GetTask task = new GetTask();
task.getStatus(); // here is always RUNNING
int instance = GetTask.getInstance();
if (instance != 1) {
final ProgressDialog dialog = new ProgressDialog(ToursListActivity.this);
dialog.setMessage("Loading...");
dialog.show();
// I also need to pause here until AsyncTask is done.
}
listener.onTaskCompleted(1); // error here
OnTaskCompleteListener interface:
public interface OnTaskCompleteListener {
void onTaskCompleted(int status);
}
I'm not sure I'm doing it right with all there CompleteListener.
As I understood, to make CompleteListener work it should be started with an Activity which I'm going to listen, but my AsyncTask already running and I don't execute it from ActivityB.
How to make it better? Or why I don't get into onTaskCompleteListener method?
I changed GetTask executing code in ActivityA to listener.onTaskCompleted(1); and getting the same error at line listener.onTaskCompleted(1); in ActivityB.
NullPointerException
Upd
ActivityB ListView dependens on ListItem which user will tap. So I think I can't load ListView before AsyncTask completed.
Solution
Well, I made it using BroadcastReceiver and static method in my AsyncTask to find out if AsyncTask completed before ActivityB is started.
Here is my code about it.
In GetTask class I added method:
static boolean taskStatus = false;
public static boolean GetTaskStatus() {
return taskStatus;
}
in onPostExecute()
Intent intent = new Intent("ru.myapp.asynctaskcompleted");
context.sendBroadcast(intent);
ActivityB
private ProgressDialog dialog;
protected void onCreate(Bundle savedInstanceState) {
...
dialog = new ProgressDialog(ActivityB.this);
taskStatus = GetTask.GetTaskStatus();
...
if (!taskStatus) { // check if AsyncTask already completed
dialog.setMessage("Loading...");
dialog.show();
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
} else {
items = datasource.getSelectedItems(cid);
setUpView(context, items);
taskStatus = false; // in case of reloading data this should be returned to false I think
}
private BroadcastReceiver asynctaskcompleted = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "AsyncTask completed");
datasource = new ItemsListDataSource(context);
datasource.open();
items = datasource.getSelectedItems(cid);
setUpView(context, items);
dialog.dismiss();
}
};
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("ru.myapp.asynctaskcompleted");
filter.addCategory("android.intent.category.DEFAULT");
registerReceiver(asynctaskcompleted, filter);
}
public void onPause() {
super.onPause();
unregisterReceiver(asynctaskcompleted);
}
Here is the link to another question I used;
That's it. Thank you for your help.
You don't need to call getStatus(), you don't need to create a new interface OnTaskCompleteListener, and you don't need getInstance()
Here's how you should do it.
mProgressDialog.show();
new GetTask()
{
#Override
protected void onPostExecute(Void result)
{
mProgressDialog.dismiss();
//this means the task is done.
}
}.execute(this, null);
Load ListView in background AsyncTask
Refer to the old exercise "ListView with icon loaded from internet", it's a time-consume task to load bitmap from internet. So the code is modified in this exercise, a AsyncTask is implemented to handle the ListView: the bitmap is loaded in background thread, and setListAdapter() in onPostExecute().
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/icon"/>
<TextView
android:id="#+id/weekofday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
AndroidList.java
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidList extends ListActivity {
public class backgroundLoadListView extends
AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
setListAdapter(new MyCustomAdapter(AndroidList.this, R.layout.row, month));
Toast.makeText(AndroidList.this,
"onPostExecute \n: setListAdapter after bitmap preloaded",
Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Toast.makeText(AndroidList.this,
"onPreExecute \n: preload bitmap in AsyncTask",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
preLoadSrcBitmap();
return null;
}
}
String image_URL=
"http://4.bp.blogspot.com/_C5a2qH8Y_jk/StYXDpZ9-WI/AAAAAAAAAJQ/sCgPx6jfWPU/S1600-R/android.png";
public class MyCustomAdapter extends ArrayAdapter<String> {
Bitmap bm;
public MyCustomAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
bm = srcBitmap;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
TextView label=(TextView)row.findViewById(R.id.weekofday);
label.setText(month[position]);
ImageView icon=(ImageView)row.findViewById(R.id.icon);
icon.setImageBitmap(bm);
return row;
}
}
Bitmap srcBitmap;
private void preLoadSrcBitmap(){
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
srcBitmap = LoadImage(image_URL, bmOptions);
}
String[] month = {
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
/*setListAdapter(new ArrayAdapter<String>(this,
R.layout.row, R.id.weekofday, DayOfWeek));*/
new backgroundLoadListView().execute();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
//super.onListItemClick(l, v, position, id);
String selection = l.getItemAtPosition(position).toString();
Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
}
private Bitmap LoadImage(String URL, BitmapFactory.Options options)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException{
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try{
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
}
catch (Exception ex){
}
return inputStream;
}
}
[Reference] [Load ListView in background AsyncTask]1

getWidth() method returns 0

I am building an activity that shows two horizontal scroll views. The top one holds large images while the lower one holds the thumbnails of those images. When the user clicks on a thumbnail the upper scroll view will automatically scroll to the image corresponding to the thumbnail. My problem is that getWidth() method of layout always returns 0. I am creating the layout at runtime and then calling the getwidth() method so it should return the correct value but it is not.
public class ZoomActivity extends Activity {
private final String THUMBS="http://kurdshopping.net/thumbs/";
private final String UPLOADS="http://kurdshopping.net/uploads/";
private ImageView imageView;
private String path;
private String[] filenames;
private LinearLayout l1,l2;
private int[] widths=null;
private HorizontalScrollView hsv=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_zoom);
ActionBarUtils.setActionBar(this);
path = getIntent().getExtras().getString("path");
filenames=getIntent().getExtras().getStringArray("images");
widths=new int[filenames.length];
l1=(LinearLayout) findViewById(R.id.LinearLayout1);
l2=(LinearLayout) findViewById(R.id.LinearLayout2);
hsv=(HorizontalScrollView) findViewById(R.id.horizontalScrollView1);
for(int i=0; i<filenames.length; i++){
BitmapLoaderTask task = new BitmapLoaderTask(i);
task.execute(UPLOADS+filenames[i],"1");
}
for(int i=0;i<filenames.length;i++){
BitmapLoaderTask task = new BitmapLoaderTask(i);
task.execute(THUMBS+filenames[i],"2");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.zoom, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
// case R.id.action_all:
// Intent allitemIntent = new Intent(MainActivity.this,
// AllItemsActivity.class);
// startActivity(allitemIntent);
// break;
// case R.id.action_search:
// Intent search = new Intent(this, SearchDialogActivity.class);
// startActivity(search);
// break;
}
return super.onOptionsItemSelected(item);
}
private void setImageBitmap(Bitmap bmp) {
imageView = new ScrollableImageView(this);
imageView.setLayoutParams(new LayoutParams(bmp.getWidth(), bmp
.getHeight()));
imageView.setImageBitmap(bmp);
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
root.addView(imageView);
}
private class BitmapLoaderTask extends AsyncTask<String, Void, Bitmap> {
private String layout;
private int index;
private int x_coords=0;
public BitmapLoaderTask(int index){
super();
this.index=index;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
setProgressBarIndeterminateVisibility(true);
}
#Override
protected synchronized Bitmap doInBackground(String... params) {
// AssetManager assets = getAssets();
Bitmap bmp = null;
layout=params[1];
try {
URL url = new URL(params[0]);
bmp = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
} catch (IOException e) {
Log.e("ZoomActivity", e.getMessage(), e);
}
return bmp;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
View view=null;
try {
view=ImageUtils.insertPhoto(ZoomActivity.this, result);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(layout.equals("1")){
l1.addView(view);
view.setTag(x_coords);
x_coords+=((LinearLayout)view).getMeasuredWidth();// this is always returning 0, view.getLayoutParams().width is also same.
}else{
l2.addView(view);
ImageView img=(ImageView) ((LinearLayout)view).getChildAt(0);
img.setTag(index);
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int index=(Integer) v.getTag();
LinearLayout layout = (LinearLayout) l1.getChildAt(index);
int x=(Integer) layout.getTag();
hsv.scrollTo(x, 0);
}
});
}
// ImageView imageview=(ImageView) findViewById(R.id.imageView1);
// imageview.setImageBitmap(result);
// setImageBitmap(result);
setProgressBarIndeterminateVisibility(false);
}
}
}
The insertPhoto function where I am creating the layout-
public static View insertPhoto(final Activity activity, Bitmap bm) throws MalformedURLException, IOException {
LinearLayout layout = new LinearLayout(activity.getApplicationContext());
layout.setLayoutParams(new LayoutParams(bm.getWidth()+10, bm.getHeight()+10));
layout.setGravity(Gravity.CENTER);
final ImageView imageView = new ImageView(
activity.getApplicationContext());
imageView.setLayoutParams(new LayoutParams(bm.getWidth(), bm.getHeight()));
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageBitmap(bm);
// imageView.setTag(filename);
layout.addView(imageView);
return layout;
}
Thanks in advance for the help.
Edit: I am posting only the portion of the code that needs the width. I modified it to use viewtreeoserver but it still doesn't work -
l1.addView(view);
view.setTag(x_coords);
view.requestLayout();
ViewTreeObserver vto=view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
x_coords+=((LinearLayout)view).getMeasuredWidth();
}
});
Try this code before using get width method-
yourlayout.requestLayout();
Hope this helps you!!!
If it is not working please let me know i will try to help you more.
Edit answer
try this code-
l1.addView(view);
view.setTag(x_coords);
view.requestLayout();
ViewTreeObserver vto=view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
x_coords+=((LinearLayout)view).getMeasuredWidth();
}
});

Categories

Resources