Drag and Drop in android web view for image - android

I want to do the drag and drop operation in android web view for the images in the webpages.
Code is like this.
WebView webView;
ImageView imageView;
ImageView shadowImageView;
private static final String IMAGEVIEW_TAG = "icon bitmap";
public static final String TAG="ResourceSharing";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser);
webView=(WebView) findViewById(R.id.webView);
imageView=(ImageView) findViewById(R.id.downloadImage);
webView.setWebViewClient(new WebViewController());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.picasaweb.google.com");
webView.clearCache(true);
webView.setOnLongClickListener(this);
shadowImageView=new ImageView(this);
shadowImageView.setImageBitmap( BitmapFactory.decodeResource(getResources(), R.drawable.picasa_logo));
shadowImageView.setTag(IMAGEVIEW_TAG);
}
public class WebViewController extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onLongClick(View v) {
HitTestResult hitTestResult=webView.getHitTestResult();
Log.i(TAG, "Hit type"+hitTestResult.getType());
switch (hitTestResult.getType()) {
case HitTestResult.IMAGE_TYPE:
Log.i(TAG, "Ïnside image type");
imageView.setVisibility(View.VISIBLE);
break;
case HitTestResult.IMAGE_ANCHOR_TYPE:
Log.i(TAG, "Ïnside image type");
imageView.setVisibility(View.VISIBLE);
break;
case HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Log.i(TAG, "Ïnside image type");
imageView.setVisibility(View.VISIBLE);
performDragAndDropOperation();
break;
default:
break;
}
return true;
}
#TargetApi(11)
private void performDragAndDropOperation(){
ClipData.Item item = new ClipData.Item((CharSequence) shadowImageView.getTag());
ClipData dragData = new ClipData((CharSequence) shadowImageView.getTag(),new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN },item);
DragShadowBuilder shadowBuilder = new MyDragShadowBuilder(shadowImageView);
shadowImageView.startDrag(dragData, shadowBuilder, null, 0);
}
private static class MyDragShadowBuilder extends View.DragShadowBuilder {
private static Drawable shadow;
public MyDragShadowBuilder(View v) {
super(v);
shadow = new ColorDrawable(Color.LTGRAY);
}
#Override
public void onProvideShadowMetrics (Point size, Point touch){
int width;
int height;
Log.i(TAG, "calling getVIew" +getView());
width = getView().getWidth() / 2;
height = getView().getHeight() / 2;
shadow.setBounds(0, 0, width, height);
size.set(width, height);
touch.set(width / 2, height / 2);
Log.i(TAG, "calling getVIew" +getView());
}
#Override
public void onDrawShadow(Canvas canvas) {
Log.i(TAG, "calling getVIew" +getView());
shadow.draw(canvas);
}
}
But when i run the application and try to drag an image after long press an error is coming in the logcat unable to initiate drag in andriod with null pointer exception.
Looking for help

Related

Live wallpaper not change in Android device when set another live wallpaper

I am new to Android development and currently I am implementing Live wallpaper application.So, My question is How I can change live wallpaper when new live wallpaper is selected from the application.currently I am setting only one live wallpaper from my application but issue is that when I am selecting wallpaper from my application to set as wallpaper it is not change and display previously selected wallpaper.And when i am restarting my device then it will display.I am using Glide library to display Gif image.
Here this my WallpaperService class
public class GifPaperService extends WallpaperService {
static final String TAG = "gifService";
static final Handler gifHandler = new Handler();
int position;
boolean visible;
ImageAdapter img = new ImageAdapter();
Integer[] mThumb = img.mThumbIds;
#Override
public void onCreate() {
super.onCreate();
Log.v("Helllo", "...");
}
#Override
public Engine onCreateEngine() {
try {
return new GifEngine();
} catch (IOException e) {
Log.w(TAG, "Error creating engine", e);
stopSelf();
return null;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("Hello..", ".....");
return super.onStartCommand(intent, flags, startId);
}
class GifEngine extends Engine {
private final Movie gif;
private final int duration;
private final Runnable runnable;
float scaleX;
float scaleY;
int when;
long start;
GifEngine() throws IOException {
MyPreferenceActivity myPref = new MyPreferenceActivity(getApplicationContext());
Log.i("Imageis... ", "Position.." + myPref.getGifImage());
position = myPref.getGifImage();
InputStream is = getResources().openRawResource(mThumb[position]);
Log.i("Imageposition...", "...." + mThumb[position]);
if (is == null) {
throw new IOException("Unable to open whoa.gif");
}
try {
gif = Movie.decodeStream(is);
duration = gif.duration();
} finally {
is.close();
}
when = -1;
runnable = new Runnable() {
#Override
public void run() {
animateGif();
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
gifHandler.removeCallbacks(runnable);
}
#Override
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
if (visible) {
animateGif();
} else {
gifHandler.removeCallbacks(runnable);
}
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
super.onSurfaceChanged(holder, format, width, height);
scaleX = width / (1f * gif.width());
scaleY = height / (1f * gif.height());
animateGif();
}
#Override
public void onOffsetsChanged(float xOffset, float yOffset,
float xOffsetStep, float yOffsetStep,
int xPixelOffset, int yPixelOffset) {
super.onOffsetsChanged(
xOffset, yOffset,
xOffsetStep, yOffsetStep,
xPixelOffset, yPixelOffset);
animateGif();
}
void animateGif() {
tick();
SurfaceHolder surfaceHolder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
if (canvas != null) {
gifCanvas(canvas);
}
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
gifHandler.removeCallbacks(runnable);
if (isVisible()) {
gifHandler.postDelayed(runnable, 1000L / 25L);
}
}
void tick() {
if (when == -1L) {
when = 0;
start = SystemClock.uptimeMillis();
} else {
long diff = SystemClock.uptimeMillis() - start;
when = (int) (diff % duration);
}
}
void gifCanvas(Canvas canvas) {
canvas.save();
canvas.scale(scaleX, scaleY);
gif.setTime(when);
gif.draw(canvas, 0, 0);
canvas.restore();
}
#Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
stopSelf();
gifHandler.removeCallbacks(runnable);
}
}
}
Activity class for setting wallpaper
setWallpaper.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT > 15) {
Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(mContext, GifPaperService.class));
startActivity(intent);
}
}
});
ImageAdapter:
public class ImageAdapter extends BaseAdapter {
static WallpaperInfo info;
private Context mContext;
public ImageAdapter() {
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return 0;
}
public ImageAdapter(Context c) {
mContext = c;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null){
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(3, 3, 3, 3);
imageView.setMaxHeight(300);
imageView.setMaxWidth(300);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyPreferenceActivity myPref = new MyPreferenceActivity(mContext);
myPref.setGifImage(position);
Intent intent = new Intent(mContext, FullScreenImage.class);
intent.putExtra("imageID", mThumbIds[position]);
/*intent.putExtra(EXTRA_LIVE_WALLPAPER_INTENT, intent);
intent.putExtra(EXTRA_LIVE_WALLPAPER_SETTINGS, info.getSettingsActivity());
intent.putExtra(EXTRA_LIVE_WALLPAPER_PACKAGE, info.getPackageName());*/
mContext.startActivity(intent);
}
});
Animation anim = AnimationUtils.loadAnimation(mContext.getApplicationContext(), R.anim.fly);
imageView.setAnimation(anim);
anim.start();
}
else{
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
public Integer[] mThumbIds = {
R.drawable.gpp1, R.drawable.gpp2,
R.drawable.gpp3,R.drawable.gpp4,
R.drawable.gpp5,R.drawable.gpp6,
R.drawable.gpp7,R.mipmap.h8,
R.mipmap.h9,R.mipmap.h10,
R.mipmap.h11,R.drawable.gp3,
R.drawable.gp2,R.drawable.gp,
R.drawable.onehalloween
};
}
If anyone know what is the problem.Tell me.
Thank in advance
For destroying previous wallpaper and setting new wallpaper,You have to Clear previous wallpaper like this,
In Your setWallpaper button click event use this code,
setWallpaper.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT > 16) {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
wallpaperManager.clear();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(mContext, GifPaperService.class));
Log.i("Intent....", "...." + intent);
startActivity(intent);
}
}
});
This is works for me...

Custom Emoji Keyboard in Android with Images

I want to create my own emoji keyboard in android. User should be able to select this keyboard as an input method for his android phone.
I tried creating it and I am able to use it in my app but I have no idea how to make this as an input method so this keyboard will be available to all other apps in my phone.
I read somewhere that I have to create a service for that so that it bind with input service.Other than that I am not able to understand rest of the thing.
Here is what I did. Though it is different from what I want to do but is start and don't know how to proceed further.
public class MainActivity extends FragmentActivity implements EmoticonsGridAdapter.KeyClickListener {
private static final int NO_OF_EMOTICONS = 100;
private ListView chatList;
private View popUpView;
private ArrayList<Spanned> chats;
private ChatListAdapter mAdapter;
private LinearLayout emoticonsCover;
private PopupWindow popupWindow;
private int keyboardHeight;
private EditText content;
private LinearLayout parentLayout;
private boolean isKeyBoardVisible;
private Bitmap[] emoticons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chatList = (ListView) findViewById(R.id.chat_list);
parentLayout = (LinearLayout) findViewById(R.id.list_parent);
emoticonsCover = (LinearLayout) findViewById(R.id.footer_for_emoticons);
popUpView = getLayoutInflater().inflate(R.layout.emoticons_popup, null);
// Setting adapter for chat list
chats = new ArrayList<Spanned>();
mAdapter = new ChatListAdapter(getApplicationContext(), chats);
chatList.setAdapter(mAdapter);
chatList.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (popupWindow.isShowing())
popupWindow.dismiss();
return false;
}
});
// Defining default height of keyboard which is equal to 230 dip
final float popUpheight = getResources().getDimension(
R.dimen.keyboard_height);
changeKeyboardHeight((int) popUpheight);
// Showing and Dismissing pop up on clicking emoticons button
ImageView emoticonsButton = (ImageView) findViewById(R.id.emoticons_button);
emoticonsButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!popupWindow.isShowing()) {
popupWindow.setHeight((int) (keyboardHeight));
if (isKeyBoardVisible) {
emoticonsCover.setVisibility(LinearLayout.GONE);
} else {
emoticonsCover.setVisibility(LinearLayout.VISIBLE);
}
popupWindow.showAtLocation(parentLayout, Gravity.BOTTOM, 0, 0);
} else {
popupWindow.dismiss();
}
}
});
readEmoticons();
enablePopUpView();
checkKeyboardHeight(parentLayout);
enableFooterView();
}
/**
* Reading all emoticons in local cache
*/
private void readEmoticons () {
emoticons = new Bitmap[NO_OF_EMOTICONS];
for (short i = 0; i < NO_OF_EMOTICONS; i++) {
emoticons[i] = getImage((i+1) + ".png");
}
}
/**
* Enabling all content in footer i.e. post window
*/
private void enableFooterView() {
content = (EditText) findViewById(R.id.chat_content);
content.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (popupWindow.isShowing()) {
popupWindow.dismiss();
}
}
});
final Button postButton = (Button) findViewById(R.id.post_button);
postButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (content.getText().toString().length() > 0) {
Spanned sp = content.getText();
chats.add(sp);
content.setText("");
mAdapter.notifyDataSetChanged();
}
}
});
}
/**
* Overriding onKeyDown for dismissing keyboard on key down
*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (popupWindow.isShowing()) {
popupWindow.dismiss();
return false;
} else {
return super.onKeyDown(keyCode, event);
}
}
/**
* Checking keyboard height and keyboard visibility
*/
int previousHeightDiffrence = 0;
private void checkKeyboardHeight(final View parentLayout) {
parentLayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Rect r = new Rect();
parentLayout.getWindowVisibleDisplayFrame(r);
int screenHeight = parentLayout.getRootView()
.getHeight();
int heightDifference = screenHeight - (r.bottom);
if (previousHeightDiffrence - heightDifference > 50) {
popupWindow.dismiss();
}
previousHeightDiffrence = heightDifference;
if (heightDifference > 100) {
isKeyBoardVisible = true;
changeKeyboardHeight(heightDifference);
} else {
isKeyBoardVisible = false;
}
}
});
}
/**
* change height of emoticons keyboard according to height of actual
* keyboard
*
* #param height
* minimum height by which we can make sure actual keyboard is
* open or not
*/
private void changeKeyboardHeight(int height) {
if (height > 100) {
keyboardHeight = height;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, keyboardHeight);
emoticonsCover.setLayoutParams(params);
}
}
/**
* Defining all components of emoticons keyboard
*/
private void enablePopUpView() {
ViewPager pager = (ViewPager) popUpView.findViewById(R.id.emoticons_pager);
pager.setOffscreenPageLimit(3);
pager.setBackgroundColor(Color.WHITE);
ArrayList<String> paths = new ArrayList<String>();
for (short i = 1; i <= NO_OF_EMOTICONS; i++) {
paths.add(i + ".png");
}
EmoticonsPagerAdapter adapter = new EmoticonsPagerAdapter(MainActivity.this, paths, this);
pager.setAdapter(adapter);
// Creating a pop window for emoticons keyboard
popupWindow = new PopupWindow(popUpView, LayoutParams.MATCH_PARENT,
(int) keyboardHeight, false);
/*TextView backSpace = (TextView) popUpView.findViewById(R.id.back);
backSpace.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
content.dispatchKeyEvent(event);
}
});*/
popupWindow.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss() {
emoticonsCover.setVisibility(LinearLayout.GONE);
}
});
}
/**
* For loading smileys from assets
*/
private Bitmap getImage(String path) {
AssetManager mngr = getAssets();
InputStream in = null;
try {
in = mngr.open("emoticons/" + path);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap temp = BitmapFactory.decodeStream(in, null, null);
return temp;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public void keyClickedIndex(final String index) {
ImageGetter imageGetter = new ImageGetter() {
public Drawable getDrawable(String source) {
StringTokenizer st = new StringTokenizer(index, ".");
Drawable d = new BitmapDrawable(getResources(),emoticons[Integer.parseInt(st.nextToken()) - 1]);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}
};
Spanned cs = Html.fromHtml("<img src ='"+ index +"'/>", imageGetter, null);
int cursorPosition = content.getSelectionStart();
content.getText().insert(cursorPosition, cs);
}
}
EDIT:
This is the code for custom keyboard that I have implemented but I am unable to find how to add emoji to that keyboard.
public class SimpleIME extends InputMethodService
implements KeyboardView.OnKeyboardActionListener {
private KeyboardView kv;
private Keyboard keyboard;
private View popUpView;
private boolean caps = false;
#Override
public View onCreateInputView() {
kv = (KeyboardView)getLayoutInflater().inflate(R.layout.keyboard, null);
keyboard = new Keyboard(this, R.xml.qwerty);
kv.setKeyboard(keyboard);
kv.setOnKeyboardActionListener(this);
kv.invalidateAllKeys();
popUpView = getLayoutInflater().inflate(R.layout.emoticons_popup, null);
return kv;
}
#Override
public void onKey(int primaryCode, int[] keyCodes) {
InputConnection ic = getCurrentInputConnection();
playClick(primaryCode);
switch(primaryCode){
case Keyboard.KEYCODE_DELETE :
ic.deleteSurroundingText(1, 0);
break;
case Keyboard.KEYCODE_SHIFT:
caps = !caps;
keyboard.setShifted(caps);
kv.invalidateAllKeys();
break;
case Keyboard.KEYCODE_DONE:
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
break;
case -80 :
Log.d("smiley", "smiley pressed");
break;
default:
char code = (char)primaryCode;
if(Character.isLetter(code) && caps){
code = Character.toUpperCase(code);
}
ic.commitText(String.valueOf(code),1);
}
}
private void playClick(int keyCode){
AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
switch(keyCode){
case 32:
am.playSoundEffect(AudioManager.FX_KEYPRESS_SPACEBAR);
break;
case Keyboard.KEYCODE_DONE:
case 10:
am.playSoundEffect(AudioManager.FX_KEYPRESS_RETURN);
break;
case Keyboard.KEYCODE_DELETE:
am.playSoundEffect(AudioManager.FX_KEYPRESS_DELETE);
break;
default: am.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD);
}
}
#Override
public void onPress(int primaryCode) {
}
#Override
public void onRelease(int primaryCode) {
}
#Override
public void onText(CharSequence text) {
}
#Override
public void swipeDown() {
}
#Override
public void swipeLeft() {
}
#Override
public void swipeRight() {
}
#Override
public void swipeUp() {
}
}
EDIT:
Can we copy an image from images list and paste it where keyboard is open??
The best implementation for an emoji keyboard I found was that of sliding emoji-Keyboard
It's a really good implementation, maybe with some redundant code, but still really good for understanding how to implement keyboards that do not fit the normal "button-to-text" keyboards.
UPDATE
Okay, I have now been able to successfully able to integrate the sliding emoji-keyboard into my own project 8Vim after a lot of re-factoring in both of the projects.
Essentially, all you are doing for the emoji keyboard is to create a view of the size of the keyboard and then populating that view with PNG files corresponding to the emoji's. each image acts like a button and delivers the appropriate emoji to the inputConnection.
UPDATE 2
I have extended the sliding emoji-keyboard and created a much cleaner version that should be easier to understand. Take a look at my emoji-keyboard

LiveWallpaper Background

i have problem with live wallpaper on preview mode.ie the wallpaper image doesn't fit well in landscape mode.it works great on portrait.i need your help.hope you would help me.i have added code
RajawaliRenderer.java
public class RipplesRenderer extends RajawaliRenderer {
private final int NUM_CUBES_H = 4;
private final int NUM_CUBES_V = 4;
private final int NUM_CUBES = NUM_CUBES_H * NUM_CUBES_V;
//private Animation3D[] mAnims;
private TouchRippleFilter mFilter;
private long frameCount;
private final int QUAD_SEGMENTS = 40;
int mScreenHeight,
mScreenWeight;
Gallery_Activity mm;
boolean flag_check = false;
int pos = 0;
int viewBackgroundImageName;
Bitmap texture;
SimpleMaterial planeMat;
int randPosition=1;
int change_value;
int Ripple_number,speed1;
Preferences preferences;
private MediaPlayer myplayer;
private boolean sound;
public RipplesRenderer(Context context) {
super(context);
setFrameRate(50);
this.mContext=context;
randPosition = BitmapUpdate.randomGenerator;
texture = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.gthree_one);
//sp=mContext.getSharedPreferences("wallpapersettings",0);
preferences=new Preferences(mContext);
}
protected void initScene() {
if(randPosition!=1) {
texture = BitmapUpdate.bit;
}
mCamera.setPosition(0, 0, -9);
DirectionalLight light = new DirectionalLight(0, 0, 1);
light.setPower(1f);
BaseObject3D group = new BaseObject3D();
DiffuseMaterial material = new DiffuseMaterial();
material.setUseColor(true);
mScreenHeight = GNWallpaper.hieght;
mScreenWeight = GNWallpaper.weight;
Random rnd = new Random();
planeMat = new SimpleMaterial();
Plane plane=new Plane(9,7,1,1);
//Plane plane = new Plane(4, 4, 1, 1);
plane.setRotZ(-90);
plane.setScale(1.0f);
plane.setMaterial(planeMat);
addChild(plane);
mFilter = new TouchRippleFilter();
mPostProcessingRenderer.setQuadSegments(QUAD_SEGMENTS);
mPostProcessingRenderer.setQuality(PostProcessingQuality.MEDIUM);
addPostProcessingFilter(mFilter);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
if (pos != com.themebowlapp.galaxynote3livewallpaper.Gallery_Activity.wallpaper_position || randPosition != BitmapUpdate.randomGenerator) {
texture = BitmapUpdate.bit;
pos = com.themebowlapp.galaxynote3livewallpaper.Gallery_Activity.wallpaper_position;
randPosition = BitmapUpdate.randomGenerator;
}
Ripple_number=preferences.getSpeed_controler();
speed1=Ripple_number*100;
super.onSurfaceCreated(gl, config);
}
public void onDrawFrame(GL10 glUnused) {
super.onDrawFrame(glUnused);
mFilter.setTime((float) frameCount++ *.05f);
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
super.onSurfaceChanged(gl, width, height);
mFilter.setScreenSize(width, height);
mFilter.setRippleSize((40+speed1));
planeMat.addTexture(mTextureManager.addTexture(texture));
}
public void setTouch(float x, float y) {
mFilter.addTouch(x, y, frameCount *.05f);
}
#Override
public void onTouchEvent(MotionEvent event) {
final int action = event.getAction();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
//sound
myplayer = MediaPlayer.create(getContext(), R.raw.water_drop);
myplayer.setVolume(100, 100);
myplayer.start();
myplayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer myplayer) {
myplayer.release();
}
});
setTouch(event.getX() / mScreenWeight, 1.0f - (event.getY() / mScreenHeight));
}
super.onTouchEvent(event);
}
}
Settings.java
public class Settings extends Activity {
public TextView SettingTextObj, BackgroundTextObj;
private RelativeLayout chose_background;
public Preferences preferences;
Context cont = this;
private CheckBox soundcheckbox;
private String PREFRENCES_NAME;
SharedPreferences settings;
// private Button choosebackground;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
chose_background = (RelativeLayout) findViewById(R.id.BackgroundLayoutId);
BackgroundTextObj = (TextView) findViewById(R.id.backgroundTxtViewId);
soundcheckbox = (CheckBox)findViewById(R.id.checkBox1);
settings = getSharedPreferences(PREFRENCES_NAME, 0);
Boolean isChecked = settings.getBoolean("cbx1_ischecked", false);
soundcheckbox.setChecked(isChecked);
soundcheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
private MediaPlayer myplayer;
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
Editor editor = getSharedPreferences(PREFRENCES_NAME, 0).edit();
editor.putBoolean("cbx1_ischecked", isChecked);
editor.commit();
Toast.makeText(getApplicationContext(), "Check", Toast.LENGTH_SHORT).show();
myplayer = MediaPlayer.create(getBaseContext(), R.raw.water_drop);
myplayer.setVolume(100, 100);
myplayer.start();
}
});
preferences = new Preferences(cont);
chose_background.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final String[] items = { "Phone Gallery", "Choose Background" };
AlertDialog.Builder builder = new AlertDialog.Builder(
Settings.this);
builder.setTitle("Pick a Background");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(items[0])) {
startActivity(new Intent(Settings.this, PhoneGallery_Activity.class));
} else {
startActivity(new Intent(Settings.this, Gallery_Activity.class));
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
}
GNWallpaper.java
public class GNWallpaper extends Wallpaper {
private RipplesRenderer mRenderer;
private String imageBg;
private int cvwidth;
private int cvheight;
private int visibleWidth;
private Bitmap bg;
private String LoadText;
private boolean sound;
private MediaPlayer myplayer;
public static WindowManager display;
static int height,width;
//private Integer[] mImageIds = { R.drawable.gthree_one,R.drawable.gthree_two,R.drawable.gthree_three, R.drawable.gthree_four, R.drawable.gthree_five, R.drawable.gthree_six,};
private int position;
public Engine onCreateEngine() {
display =(WindowManager) getSystemService(Context.WINDOW_SERVICE);
height= display.getDefaultDisplay().getHeight();
width= display.getDefaultDisplay().getWidth();
mRenderer = new RipplesRenderer(this);
//Log.i("shibbu"," hello");
return new WallpaperEngine(this.getSharedPreferences(SHARED_PREFS_NAME,
Context.MODE_PRIVATE), getBaseContext(), mRenderer, false);
}
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
imageBg = prefs.getString("image_custom", "Bad Image");
getBackground();
sound=prefs.getBoolean("pref_sound", false);
// //sound
// sound=prefs.getBoolean("pref_sound", false);
}
void getBackground() {
if (this.cvwidth == 0 || this.cvheight == 0 || this.visibleWidth == 0) {
this.cvwidth = 1290;
this.cvheight = 800;
this.visibleWidth = 1290;
}
if(new File(imageBg).exists()) {
int SampleSize = 1;
do {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bg = BitmapFactory.decodeFile(imageBg, options);
SampleSize = (int) (Math.ceil(options.outWidth/(this.visibleWidth * 2))*2);
options.inJustDecodeBounds = false;
try {
options.inSampleSize = SampleSize;
bg = BitmapFactory.decodeFile(imageBg, options);
} catch (OutOfMemoryError e) {
SampleSize = SampleSize * 2;
}
} while (bg == null);
bg = Bitmap.createScaledBitmap(bg, this.cvwidth/2, this.cvheight, true);
} else {
bg = BitmapFactory.decodeResource(getResources(), R.drawable.gthree_one);
//bg = BitmapFactory.decodeResource(getResources(), mImageIds[position]);
//position++;
bg = Bitmap.createScaledBitmap(bg, this.cvwidth/2, this.cvheight, true);
LoadText = "";
}
}
}
Refer this link.It will help you to change to landscape view..
http://tips4android.blogspot.in/2012/01/android-tips-how-to-get-screen.html

Drag and Drop help - Android

I'm using Android Studio to create a small drag and drop application. I have followed all the rules I know and the code doesn't seem to have any errors, however when I run it on my device it simple crashes. Anyone know where its wrong?
The code is fine until initialise(); is called in public void blue(View v)
so I'm suspecting the error is there
public class MainActivity extends Activity {
private ImageView blueball;
private ImageView blueballdrag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void colourGen(View view){
int i =1;
if (i==i){
blue(view);
}
}
public void brown(View v){
setContentView(R.layout.activity_brown);
}
public void yellow (View v){
setContentView(R.layout.activity_yellow);
}
public void green (View v){
setContentView(R.layout.activity_green);
}
public void blue (View v){
setContentView(R.layout.activity_blue);
initialise();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void initialise() {
final ImageView imageView = (ImageView) blueballdrag.findViewById(R.id.imageView4);
imageView.setOnDragListener(new View.OnDragListener() {
public boolean onDrag(View v, DragEvent dragEvent) {
switch (dragEvent.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
v.setBackgroundColor(Color.RED);
case DragEvent.ACTION_DRAG_ENTERED:
v.setBackgroundColor(Color.BLACK);
case DragEvent.ACTION_DRAG_ENDED:
v.setBackgroundColor(Color.GREEN);
case DragEvent.ACTION_DROP:
v.setBackgroundColor(Color.WHITE);
}
return false;
}
});
blueball = (ImageView) findViewById(R.id.imageView6);
blueball.setOnLongClickListener(new OnLongClickListener(){
#Override
public boolean onLongClick(View v) {
View.DragShadowBuilder myShadow = new MyDragShadowBuilder(blueball);
v.startDrag(null, myShadow, null, 0);
return false;
}
});
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static class MyDragShadowBuilder extends View.DragShadowBuilder {
private static Drawable shadow;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public MyDragShadowBuilder(View v) {
super(v);
shadow = new ColorDrawable(Color.RED);
}
public void onProvideShadowMetrics(Point size, Point touch){
int width, height;
width = getView().getWidth() * 2;
height = getView().getHeight() * 2;
shadow.setBounds(0, 0, width, height);
size.set(width, height);
touch.set(width*2, height*2);
}
public void onDrawShadow(Canvas canvas){
shadow.draw(canvas);
}
}
}
The problem is the line
final ImageView imageView = (ImageView) blueballdrag.findViewById(R.id.imageView4);
This line tells the Object blueballdrag to find a child view called imageView4. I'm guessing that your ImageViews don't have children. You want the findViewById() method of your Activity, not your View.
Changing the line to the following should solve your problem.
final ImageView imageView = (ImageView) findViewById(R.id.imageView4);

Implementing OnTouchListener on LinearLayout - Android Development

public class UnitConverterActivity extends Activity implements OnTouchListener {
/** Called when the activity is first created. */
LinearLayout mLinearLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLinearLayout = new LinearLayout(this);
ImageView i = new ImageView(this);
i.setImageResource(R.drawable.mainmenu);
//i.setAdjustViewBounds(false);
i.setScaleType(ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mLinearLayout.addView(i);
setContentView(mLinearLayout);
//setContentView(R.layout.main);
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
}
I have used the above method to load an image for the main menu I am trying to create. The image has four areas and each will be used to call a particular function of the app. Now I am trying to implement touch interface on those areas. I know how to define the range of pixels for that purpose but I am at loss on how to implement OnTouchListner on the image. Please help me in this regard.
If your image was split into four rectangular quarters (say)
then in onCreate have:
i.setOnTouchListener(this);
and for your listener, something like this (illustrates the principle only):
#Override
public boolean onTouch(View v, MotionEvent mev) {
int width = v.getWidth();
int height = v.getHeight();
float x = mev.getX();
float y = mev.getY();
String msg;
if (x < width / 2) {
if (y < height / 2)
msg = "Top left quarter";
else
msg = "Bottom left quarter";
} else {
if (y < height / 2)
msg = "Top right quarter";
else
msg = "Bottom right quarter";
}
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
return false;
}
Just put this code in onCreate().
i.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//your code
}
}

Categories

Resources