I'm doing a lockscreen with gridview puzzle i have successfully trigered lockscreen on Screen of and screen on when i have only buttons in my lockscrean when i add grid view in my lockscreen the activity is not coming when i screen on.
Below is my Lockscreen Service without gridview:
public class LockscreenService extends Service {
private LinearLayout linearLayout;
private WindowManager.LayoutParams layoutParams;
private WindowManager windowManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
BroadcastReceiver screenReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF) && linearLayout == null) {
init();
}
}
};
#Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(screenReceiver, intentFilter);
windowManager = ((WindowManager) getSystemService(WINDOW_SERVICE));
layoutParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION,
PixelFormat.TRANSLUCENT);
}
private void init() {
linearLayout = new LinearLayout(this);
windowManager.addView(linearLayout, layoutParams);
((LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.lockscreen, linearLayout);
// View btnClose = linearLayout.findViewById(R.id.button);
View btnClose = linearLayout.findViewById(R.id.button8);
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something when the corky3 is clicked
windowManager.removeView(linearLayout);
linearLayout = null;
}
});
}
it gives a lock screen like this lockscreen without gridview
When i add lockscreen to the linearlayout in init() methid like this
public class LockscreenService extends Service {
String p;
ImageView myImage;
final ArrayList<Bitmap> beforeshuffle = new ArrayList<>(9);
final ArrayList<Bitmap> aftershuffle = new ArrayList<>(9);
ArrayList<Bitmap> smallimages = new ArrayList<Bitmap>(9);
GridView grid;
Bitmap bs;
Bitmap as;
private LinearLayout linearLayout;
private WindowManager.LayoutParams layoutParams;
private WindowManager windowManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
BroadcastReceiver screenReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF) && intent.getAction().equals(Intent.ACTION_SCREEN_ON)&& linearLayout == null) {
init();
}
}
};
#Override
public void onCreate() {
Log.d("jhg","inservice");
super.onCreate();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(screenReceiver, intentFilter);
windowManager = ((WindowManager) getSystemService(WINDOW_SERVICE));
layoutParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION,
PixelFormat.TRANSLUCENT);
}
private void init() {
// Log.d("hdkjfh","in init");
linearLayout = new LinearLayout(this);
windowManager.addView(linearLayout, layoutParams);
((LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.lockscreen, linearLayout);
// View btnClose = linearLayout.findViewById(R.id.button);
// grid = (GridView) linearLayout.findViewById(R.id.gridView);
// grid = (GridView) findViewById(R.id.gridView);
Globalvariable c = new Globalvariable();
String p = c.givedata();
Log.d("fg", p);
bs = c.giveBitmap();
// Bitmap bitmap = (Bitmap) i.getParcelableExtra("bitmap");
//smallimage_Numbers is to tell how many smallimage_s the image should split
int smallimage_Numbers = 9;
//Getting the source image to split
// ImageView image = (ImageView) findViewById(R.id.source_image);
// File imgFile = new File("profile.jpg"
Bitmap myBitmap = BitmapFactory.decodeFile(p);
//Drawable d = new BitmapDrawable(getResources(), myBitmap);
// myImage= (ImageView) linearLayout.findViewById(R.id.My);
// myImage = (ImageView) findViewById(R.id.My);
// myImage.setImageBitmap(myBitmap);
// myImage.setVisibility(View.INVISIBLE);
splitImage(myBitmap, smallimage_Numbers);
View btnClose = linearLayout.findViewById(R.id.button8);
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something when the corky3 is clicked
Bitmap as = getBitmapFromView(grid);
if (bs.sameAs(as)) {
Toast.makeText(getApplicationContext(), "CORRECT", Toast.LENGTH_SHORT).show();
windowManager.removeView(linearLayout);
linearLayout = null;
} else {
Toast.makeText(getApplicationContext(), "WRONG", Toast.LENGTH_SHORT).show();
}
}
});
}
//invoking this method makes the actual splitting of the source image to given number of smallimage_s
//Image.setImageBitmap(decodeSampledBitmapFromFile(file.getAbsolutePath(), 500, 250));
/**
* Splits the source image and show them all into a grid in a new activity
*
* #param
* #param smallimage_Numbers The target number of small image smallimage_s to be formed from the source image
*/
public void splitImage(Bitmap bit, int smallimage_Numbers) {
//For the number of rows and columns of the grid to be displayed
int rows, cols;
//For height and width of the small image smallimage_s
int smallimage_Height, smallimage_Width;
//To store all the small image smallimage_s in bitmap format in this list
smallimages = new ArrayList<Bitmap>(smallimage_Numbers);
//Getting the scaled bitmap of the source image
// BitmapDrawable mydrawable = (BitmapDrawable) image.getDrawable();
Bitmap bitmap = bit;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
rows = cols = (int) Math.sqrt(smallimage_Numbers);
smallimage_Height = bitmap.getHeight() / rows;
smallimage_Width = bitmap.getWidth() / cols;
//xCo and yCo are the pixel positions of the image smallimage_s
int yCo = 0;
for (int x = 0; x < rows; x++) {
int xCo = 0;
for (int y = 0; y < cols; y++) {
smallimages.add(Bitmap.createBitmap(scaledBitmap, xCo, yCo, smallimage_Width, smallimage_Height));
xCo += smallimage_Width;
}
yCo += smallimage_Height;
}
Array[] in = new Array[9];
//Collections.shuffle(smallimages);
grid.setAdapter(new ImageAdapter(this, smallimages));
grid.setNumColumns((int) Math.sqrt(smallimages.size()));
Collections.shuffle(smallimages);
grid.setAdapter(new ImageAdapter(this, smallimages));
grid.setNumColumns((int) Math.sqrt(smallimages.size()));
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
int counter = 0;
int firstclick;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
counter++;
if (counter % 2 == 0) {
firstclick = position;
Bitmap data1 = smallimages.get(position);
} else {
Bitmap swapImage = smallimages.get(position);
smallimages.set(position, smallimages.get(firstclick));
smallimages.set(firstclick, swapImage);
grid.invalidateViews();
}
for (int i = 0; i < smallimages.size(); i++) {
aftershuffle.add(smallimages.get(i));
}
}
});
//activity to show these smallimage_s into a grid
}
//to compare two bitmaps in gridview
{
#Override
public void onClick (View v){
Bitmap as = getBitmapFromView(grid);
if (bs.sameAs(as)) {
Toast.makeText(getApplicationContext(), "CORRECT", Toast.LENGTH_SHORT).show();
windowManager.removeView(linearLayout);
linearLayout = null;
} else {
Toast.makeText(getApplicationContext(), "WRONG", Toast.LENGTH_SHORT).show();
}
}
});
*/
public static Bitmap getBitmapFromView(View view){
Bitmap bitmap =Bitmap.createBitmap(view.getWidth(),view.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas =new Canvas(bitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable!=null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return bitmap;
}
}
it returns nothing when i click screen on and off. Help me to show my shuffled grid view in my lockscreen.
I don't find the place where you make reference to the GridView "grid". Are those two lines intended to be commented? Also can you provide the implementation of your ImageAdapter?
Related
Hello there,
I'm kind of new to Android, and I'm working on a simple image gallery. I have photo that is turned into Bitmap, then I cut it into 9 square(or equal) elements. Afterwards, I'm placing it to a GridView using my version of ImageAdapter. At last I want to make an effect that this squares randomly become transparent(gradient like from visible to transparent) and reavel another image beneath them(So the process can be repeated infinitely). I want to make it OnClick later to change photo, but right now I can't figure out how to make certain elements of GridView transparent. I tried using getChildAt(int index) or getItemAtPosition(int position) but all I get was NullPointerException. Can anyone help me with this? I tried to use many code samples across the web but none of it make it possible.
My main Activity:
public class MainActivity extends AppCompatActivity {
private int screenX;
private int screenY;
private ArrayList<Bitmap> chunkedImages;
private GridView gv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
RelativeLayout rl = (RelativeLayout)findViewById(R.id.RelativeLayout1);
rl.setBackgroundColor(Color.BLACK);
loadScreenXY();
ImageView view = new ImageView(this);
view.setImageResource(R.drawable.pizza);
this.chunkedImages = this.splitImage(view,9);
gv = (GridView) findViewById(R.id.GridView);
gv.setAdapter(new GridImageAdapter(this,this.chunkedImages));
gv.setNumColumns(3);
}
private void loadScreenXY() {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
this.screenX = size.x;
this.screenY = size.y;
}
private ArrayList<Bitmap> splitImage(ImageView image, int chunkNumbers) {
int rows,cols;
int chunkHeight;
int chunkWidth;
ArrayList<Bitmap> chunkedImages = new ArrayList<Bitmap>(chunkNumbers);
BitmapDrawable drawable = (BitmapDrawable) image.getDrawable();
Bitmap bitmap = drawable.getBitmap();
rows = cols = (int) Math.sqrt(chunkNumbers);
chunkHeight = bitmap.getHeight()/rows;
chunkWidth = bitmap.getWidth()/cols;
int yCoord = 0;
for(int x=0; x<rows; x++){
int xCoord = 0;
for(int y=0; y<cols; y++){
chunkedImages.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkWidth, chunkHeight));
xCoord += chunkWidth;
}
yCoord += chunkHeight;
}
return chunkedImages;
}
And my Adapter:
public class GridImageAdapter extends BaseAdapter{
private Context mContext;
private ArrayList<Bitmap> bm;
public GridImageAdapter(Context c, ArrayList<Bitmap> bm) {
mContext = c;
this.bm = bm;
}
public int getCount() {
return this.bm.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(this.bm.get(position).getWidth(),this.bm.get(position).getHeight()));
imageView.setPadding(0,0,0,0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(this.bm.get(position));
return imageView;
}
}
I have popupWindow with some image views, which are created and added progammatically to popup window. Their position is set to bottom line with setY(). But when I use setEndValue to animate with spring, image goes from 0 to setEndValue, not from it's initial position.
How that can be fixed?
public SharePostPopupWindow(View parentView) {
super(MATCH_PARENT, MATCH_PARENT);
this.context = parentView.getContext();
this.parentView = parentView;
AndroidBlaBlaApplication.component(context).inject(this);
setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
FrameLayout container = new FrameLayout(context);
socialViews = new ArrayList<>();
socials = new ArrayList<>();
shadow = new View(context);
shadow.setId(R.id.share_view_shadow);
shadow.setBackgroundColor(Color.BLACK);
shadow.setClickable(true);
shadow.setAlpha(0.5f);
shadow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bus.post(new ShadowClickedEvent());
spring.setEndValue(initialPosition / 2 - Utils.convertDpToPixel(imageSize, context));
dismiss();
}
});
}
public void show() {
Utils.hideKeyboard(context, getContentView());
createButtons();
SpringSystem springSystem = SpringSystem.create();
spring = springSystem.createSpring();
SpringConfig slowConfig = new SpringConfig(TENSION, DAMPER);
spring.setSpringConfig(slowConfig);
spring.addListener(new SimpleSpringListener() {
#Override
public void onSpringUpdate(Spring spring) {
float value = (float) spring.getCurrentValue();
for (int i = 0; i < socialViews.size(); i++) {
if (i % 2 != 0) {
socialViews.get(i).setY(value);
}
}
}
});
showAtLocation(parentView, Gravity.CENTER_VERTICAL, 0, 0);
getContentView().setAlpha(1f);
}
If you want to force spring animation from certain position, you need to use
spring.setCurrentValue method first.
I found a tutorial on the Internet for an image slider but I don't know how to make it work on my phone. In the emulator it is giving me a message about setting nat directory path. I don't know how to do that. . .
Could anyone help me, please?
Code for Activities are:
Code for FullScreenViewActivity.java:
public class FullScreenViewActivity extends Activity{
private Utils utils;
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
viewPager = (ViewPager) findViewById(R.id.pager);
utils = new Utils(getApplicationContext());
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,
utils.getFilePaths());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
}
}
Code for GridViewActivity.java:
public class GridViewActivity extends Activity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view);
gridView = (GridView) findViewById(R.id.grid_view);
utils = new Utils(this);
// Initilizing Grid View
InitilizeGridLayout();
// loading all image paths from SD card
imagePaths = utils.getFilePaths();
// Gridview adapter
adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,
columnWidth);
// setting grid view adapter
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
}
Code for FullScreenImageAdapter.java:
public class FullScreenImageAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this._activity = activity;
this._imagePaths = imagePaths;
}
#Override
public int getCount() {
return this._imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TouchImageView imgDisplay;
Button btnClose;
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
btnClose = (Button) viewLayout.findViewById(R.id.btnClose);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
imgDisplay.setImageBitmap(bitmap);
// close button click event
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_activity.finish();
}
});
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
public class GridViewImageAdapter extends BaseAdapter {
private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this._filePaths.size();
}
#Override
public Object getItem(int position) {
return this._filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
} else {
imageView = (ImageView) convertView;
}
// get screen dimensions
Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
imageWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
imageView.setImageBitmap(image);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
Intent i = new Intent(_activity, FullScreenViewActivity.class);
i.putExtra("position", _postion);
_activity.startActivity(i);
}
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
Code for GridViewImageAdapter.java:
public class GridViewImageAdapter extends BaseAdapter {
private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this._filePaths.size();
}
#Override
public Object getItem(int position) {
return this._filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
} else {
imageView = (ImageView) convertView;
}
// get screen dimensions
Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
imageWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
imageView.setImageBitmap(image);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
Intent i = new Intent(_activity, FullScreenViewActivity.class);
i.putExtra("position", _postion);
_activity.startActivity(i);
}
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
util.java
public class Utils {
private Context _context;
// constructor
public Utils(Context context) {
this._context = context;
}
/*
* Reading file paths from SDCard
*/
public ArrayList<String> getFilePaths() {
ArrayList<String> filePaths = new ArrayList<String>();
File directory = new File(
android.os.Environment.getExternalStorageDirectory()
+ File.separator + AppConstant.PHOTO_ALBUM);
// check for directory
if (directory.isDirectory()) {
// getting list of file paths
File[] listFiles = directory.listFiles();
// Check for count
if (listFiles.length > 0) {
// loop through all files
for (int i = 0; i < listFiles.length; i++) {
// get file path
String filePath = listFiles[i].getAbsolutePath();
// check for supported file extension
if (IsSupportedFile(filePath)) {
// Add image path to array list
filePaths.add(filePath);
}
}
} else {
// image directory is empty
Toast.makeText(
_context,
AppConstant.PHOTO_ALBUM
+ " is empty. Please load some images in it !",
Toast.LENGTH_LONG).show();
}
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(_context);
alert.setTitle("Error!");
alert.setMessage(AppConstant.PHOTO_ALBUM
+ " directory path is not valid! Please set the image directory name AppConstant.java class");
alert.setPositiveButton("OK", null);
alert.show();
}
return filePaths;
}
/*
* Check supported file extensions
*
* #returns boolean
*/
private boolean IsSupportedFile(String filePath) {
String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
filePath.length());
if (AppConstant.FILE_EXTN
.contains(ext.toLowerCase(Locale.getDefault())))
return true;
else
return false;
}
/*
* getting screen width
*/
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) _context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
}
AppConstant.java
public class AppConstant {
// Number of columns of Grid View
public static final int NUM_OF_COLUMNS = 3;
// Gridview image padding
public static final int GRID_PADDING = 8; // in dp
// SD card image directory
public static final String PHOTO_ALBUM = "NAT";
// supported file formats
public static final List<String> FILE_EXTN = Arrays.asList("jpg", "jpeg",
"png");
}
The only problem is setting the nat directory path so that it works on my phone.
I had the same problem (same tutorial :D), the problem is that you need a place to store all the wallpapers, so just change
// SD card image directory
public static final String PHOTO_ALBUM = "NAT";
to
// SD card image directory
public static final String PHOTO_ALBUM = "Camera";
for example to show the cameras pics.
public static final String PHOTO_ALBUM =Environment.getExternalStorageDirectory().getPath()+ "/DCIM/"+"/100ANDRO/";
"/DCIM/100ANDRO/" is a path where my Pictures are stored.
just change NAT by DCIM/Camera here your internal phone memory pics. i tried this and its work but some other problem occurs, when i click any pic then application is force stop if you resolve this problem then let m know. thank you
I use custom CursorAdapter with custom items.
I need height of view to resize Bitmap from assets folder and set this resized bitmap to ImegeView in list item;
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
final ViewHolder holder = (ViewHolder) view.getTag();
final int imgCol = cursor.getColumnIndex(TableOdelice.COLUMN_URL);
int titleCol = cursor.getColumnIndex(TableOdelice.COLUMN_TITRE);
final int themeCol = cursor.getColumnIndex(TableOdelice.COLUMN_THEME);
String tempPath = getPath(cursor.getString(themeCol), cursor.getString(imgCol));
final String path = tempPath.replace(".", "c.");
String[] arr = cursor.getString(titleCol).split("\\*");
holder.title.setText(arr[0]);
holder.subTitle.setText(arr[1]);
if (itemHeight > 0) {
showThumb(itemHeight, holder.img, path);
} else {
final ImageView v = holder.mainImage;
v.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
itemHeight = v.getHeight();
showThumb(itemHeight, holder.img, path);
}
});
}
}
private void showThumb(int height, final ImageView iv, final String path) {
if (thumbs.containsKey(path)) {
iv.setImageBitmap(thumbs.get(path));
} else {
InputStream is = null;
try {
is = context.getAssets().open(path);
} catch (IOException e) {
Log.d("no file at path", path);
e.printStackTrace();
}
if (is != null) {
Bitmap btm = btmHelper.scaleToHeight(BitmapFactory.decodeStream(is);, height);
thumbs.put(path, btm);
iv.setImageBitmap(btm);
}
}
}
For getting view height I use OnGlobalLayoutListener() of view.
But it's very slow ...
Any ideas?
I find answer for my question.
Using this construction I get a correct width or height of view inside adapter for each view.
final ImageView v = holder.mainImage;
v.post(new Runnable() {
#Override
public void run() {
itemHeight = v.getHeight();
Log.d("Height", "" + itemHeight);
}
});
}
Maybe it will help somebody :)
Just give it a try may be it will be faster
v.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
itemHeight = v.getHeight();
showThumb(itemHeight, holder.img, path);
v.getViewTreeObserver().removeGlobalOnLayoutListener( ActivityInsatance);
}
});
If you have top or bottom margins, a bug will appear. When you will scroll this listview, a height of each row will increase. In case of v.getViewTreeObserver().addOnGlobalLayoutListener it will grow infinitely. So, my solution follows.
holder.layout.post(new Runnable() {
#Override
public void run() {
int height = holder.layout.getMeasuredHeight(); // Total row height.
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) holder.textView.getLayoutParams();
holder.textView.setHeight(height - lp.topMargin - lp.bottomMargin);
});
where holder.layout is a link to root RelativeLayout of an adapter's row.
Can anyone help me to do this.
I am trying to build an android app but stuck in between.
i have use the following code to move a image.
iv is ImageView object
moveImage = new TranslateAnimation( 0, xDest, 0, -yDest);
moveImage.setDuration(1000);
moveImage.setFillAfter( true );
iv.startAnimation(moveImage);
code:
public class gameLogic extends Activity
{
ImageView image;
TranslateAnimation moveImage;
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.game_logic);
imageMoveRandom(imageList(image,0));
}
ImageView imageList(ImageView v,int i)
{
v = (ImageView) findViewById(R.id.rabbit);
int imgId;
int j = i;
TypedArray imgs = getResources().obtainTypedArray(R.array.random_imgs);
//get resourceid by index
imgId = imgs.getResourceId(j, 0);
// or set you ImageView's resource to the id
v.setBackgroundResource(imgId);
return v;
}
void imageMoveRandom(ImageView iv)throws NotFoundException
{
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int xDest = dm.widthPixels/2;
int yDest = dm.heightPixels/2;
// Toast.makeText(gameLogic.this, dm.widthPixels, Toast.LENGTH_SHORT).show();
// Toast.makeText(this, dm.heightPixels, 2000).show();
moveImage = new TranslateAnimation( 0, xDest, 0, -yDest);
moveImage.setDuration(1000);
moveImage.setFillAfter( true );
iv.startAnimation(moveImage);
//moveImage.reset();
}
}
Above is not full code..but part which may be helpful for references.
But i want to continuously move the image in random place but within the android display.
Can any one suggest the solution.
Thanks in Advance :)
class BitmapView extends View
{
changingX=10;
changingY=10;
public BitmapView(Context context) {
super(context);
}
#Override
public void onDraw(Canvas canvas) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.yourImageName);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(bmp, changingX,changingY, null);
changingX=changingX+5;
changingY=changingY+10;
invalidate();
}
}
Try this