How to implement pan and pinch zoom gesture into android GridView? - java

I want to make a board using android GridView as follows -
I need to make the GridView zoomable using two fingers and also pannable.
What is a standard and easy way to do this?
I'm able to make an imageview zoomable but not pannable using the following code-
public class MainActivity extends Activity {
private ImageView imageView;
private float scale = 1f;
private ScaleGestureDetector detector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)findViewById(R.id.imageView);
detector = new ScaleGestureDetector(this,new ScaleListener());
}
public boolean onTouchEvent(MotionEvent event) {
// re-route the Touch Events to the ScaleListener class
detector.onTouchEvent(event);
return super.onTouchEvent(event);
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
float onScaleBegin = 0;
float onScaleEnd = 0;
#Override
public boolean onScale(ScaleGestureDetector detector) {
scale *= detector.getScaleFactor();
imageView.setScaleX(scale);
imageView.setScaleY(scale);
return true;
}
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
Toast.makeText(getApplicationContext(),"Scale Begin" ,Toast.LENGTH_SHORT).show();
onScaleBegin = scale;
return true;
}
#Override
public void onScaleEnd(ScaleGestureDetector detector) {
Toast.makeText(getApplicationContext(),"Scale Ended",Toast.LENGTH_SHORT).show();
onScaleEnd = scale;
if (onScaleEnd > onScaleBegin){
Toast.makeText(getApplicationContext(),"Scaled Up by a factor of " + String.valueOf( onScaleEnd / onScaleBegin ), Toast.LENGTH_SHORT ).show();
}
if (onScaleEnd < onScaleBegin){
Toast.makeText(getApplicationContext(),"Scaled Down by a factor of " + String.valueOf( onScaleBegin / onScaleEnd ), Toast.LENGTH_SHORT ).show();
}
super.onScaleEnd(detector);
}
}
}
I tried by replacing the imageview part with gridview in this code. But that didn't work.How do I implement this properly?

Related

Pinch zoom only zooms into center

I‘m trying to make an image in my app pinch-zoomable. It should be able to zoom into different parts of the image. As the code is right now, wherever I‘m doing the zooming gesture it only zooms into the center, so I have no chance to move the image or zoom into other areas.
What is necessary decenter the zoom and move the zoomed image?
public class MainActivity extends AppCompatActivity {
private ScaleGestureDetector mScaleGestureDetector;
private float mScaleFactor = 1.0f;
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView)findViewById(R.id.imageView);
mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
mImageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mScaleGestureDetector.onTouchEvent(event);
return true;
}
});
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector){
mScaleFactor *= scaleGestureDetector.getScaleFactor();
mScaleFactor = Math.max(1.0f,
Math.min(mScaleFactor, 1.7f));
mImageView.setScaleX(mScaleFactor);
mImageView.setScaleY(mScaleFactor);
return true;
}
}
}
For your purposes, the best will be added this library:
https://github.com/chrisbanes/PhotoView
Of course, or add this library as local module and customize it for your purposes.

How to animate TextureView?

I am trying to fade in a TextureView but for some reason its not animating. It just simply pops in the video, no fade at all and i dont really know why that is because after some research i have found that TextureView can be animated normally.
Here is my code, i hope you guys can give me a pointer in the right direction.
PS, i have left out all irrelevant code that does not concern itself with the textureview and the animation.
public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener
{
private static final String TAG = MainActivity.class.getSimpleName();
private MediaPlayer mediaPlayer1;
private ArrayList<Uri> videoUris = new ArrayList<>();
private int current_video_index = 0;
private TextureView textureView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textureView = (TextureView) findViewById(R.id.textureView);
mediaPlayer1 = new MediaPlayer();
mediaPlayer1.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer1.setOnPreparedListener(this);
mediaPlayer1.setOnCompletionListener(this);
initVideoUris();
initNewVideo();
}
private void startVideo(final Uri uri)
{
textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener()
{
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
{
try {
mediaPlayer1.setDataSource(MainActivity.this, uri);
mediaPlayer1.setSurface(new Surface(surface));
mediaPlayer1.setOnCompletionListener(MainActivity.this);
mediaPlayer1.setOnPreparedListener(MainActivity.this);
mediaPlayer1.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer1.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height)
{
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface)
{
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface)
{
}
});
}
#Override
public void onPrepared(MediaPlayer mp)
{
mp.start();
fadeInView(textureView);
}
#Override
public void onCompletion(MediaPlayer mp)
{
if (!moreVideosAvailable())
{
finish();
}
}
private boolean moreVideosAvailable()
{
return current_video_index < videoUris.size();
}
private void fadeInView(View view)
{
view.setAlpha(0f);
view.setVisibility(View.VISIBLE);
view.animate().alpha(1f).setDuration(2000).setListener(null).start();
}
}
I solved it by making a videoPlayerFragment that uses TextureView as the surface for displaying the video. Then simply animate the whole fragment instead of the textureView.

Nothing getting drawn

This code shows nothing on my screen when run. I need to draw a simple circle wherever you touch.
public class Touchevent extends AppCompatActivity {
float mLastTouchX = 0;
float mLastTouchY = 0;
Canvas zex=new Canvas();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_touchevent);
RelativeLayout mylayout = (RelativeLayout)findViewById(R.id.test);
mylayout.setOnTouchListener(
new RelativeLayout.OnTouchListener() {
public boolean onTouch(View v, MotionEvent m) {
onTouchEvent(m);
onDraw(zex);
return true;
}
}
);
}
public void onDraw(Canvas canvasx) {
canvasx.drawColor(Color.WHITE);
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvasx.drawCircle(mLastTouchX,mLastTouchY,100,paint);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
mLastTouchX = ev.getX();
mLastTouchY = ev.getY();
return true;
}
}
The code shows no error. Do I need to add a custom view? Then how to implement a click listener?

How to use Sound with Toast in Android

I want to play a sound when my toast pops up in my android app.
Here is my code for the toast in my main class:
private void workEndNotification() {
//Custom Toast notification for the Work End Reminder.
LayoutInflater inflaterWork = getLayoutInflater();
View toastLayout = inflaterWork.inflate(R.layout.work_notification_toast, (ViewGroup) findViewById(R.id.toast_root_view));
TextView header = (TextView) toastLayout.findViewById(R.id.toast_header);
header.setText("Work Day Over Soon!");
final Toast toastWork = new Toast(getApplicationContext());
toastWork.setGravity(Gravity.CENTER, 0, 0);
toastWork.setDuration(Toast.LENGTH_SHORT);
toastWork.setView(toastLayout);
toastWork.show();
myHandler.postDelayed(new Runnable() {
public void run() {
toastWork.cancel();
}
}, 1);
};
Here is the sound code in my SoundPool class (http://www.vogella.com/tutorials/AndroidMedia/article.html):
class PlaySound extends Activity implements OnTouchListener {
private SoundPool soundPool;
private int soundID;
boolean loaded = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.work_notification_toast);
View view = findViewById(R.id.toast_header);
view.setOnTouchListener(this);
// Set the hardware buttons to control the music
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the sound
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,int status) {
loaded = true;
}
});
soundID = soundPool.load(this, R.raw.sound1, 1);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// Getting the user sound settings
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
// Is the sound loaded already?
if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
Log.e("Test", "Played sound");
}
}
return false;
}
}
I know I am not calling it in my toast method, and I know that I am using a touchview. How can I make it so the sound appears only when the toast appears, at the same time that is. I have been trying, but have not managed.
I don't want a touch or anything. Just for it to play with the toast simply.
Make a function like this
private void playSound(int resId){
mp = MediaPlayer.create(MainActivity.this, resId);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.reset();
mediaPlayer.release();
}
});
mp.start();
}
and call it where you are displaying your Toast like this
playSound(R.raw.sound);
You also need to replace the resource so it matches yours
EDIT: You seem to want to play several sounds. You can make a simple sound pool on your own
Make a int array or resource you want to play like this and listen for when the MediaPlayer is done with playing, tell him to play the next one until it played the last one in the array.
public class TestActivity extends Activity implements MediaPlayer.OnCompletionListener {
private final int[] soundResources = {R.raw.sound1, R.raw.sound2, R.raw.sound3};
private int counter = 0;
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
playSound(counter);
}
private void playSound(int resId){
mp = MediaPlayer.create(TestActivity.this, resId);
mp.setOnCompletionListener(this);
mp.start();
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mp.reset();
mp.release();
if(counter < soundResources.length ) {
playSound(soundResources[++counter]);
}
}
}

Example of how to change textView Color onTouch?

been working on a prject for a while, now I want it so that when the user touches the screen it changes the color of the textView(DigitalClock). I'm a bit of a noob when it comes to java so I really need a fully working example if possible? Here's my code so far:
public class MainActivity extends Activity {
private static final Random RANDOM = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
Handler handler = new RandomMoveHandler((TextView) findViewById(R.id.digitalClock1));
handler.sendEmptyMessage(0);
}
private static class RandomMoveHandler extends Handler {
private final WeakReference<TextView> textViewWeakReference;
private RandomMoveHandler(TextView textView) {
this.textViewWeakReference = new WeakReference<TextView>(textView);
}
#Override
public void handleMessage(Message msg) {
TextView textView = textViewWeakReference.get();
if (textView == null) {
Log.i(TAG, "WeakReference is gone so giving up.");
return;
}
int x = RANDOM.nextInt(670 - 100);
int y = RANDOM.nextInt(1230 - 100);
Log.i(TAG, String.format("Moving text view to (%d, %d)", x, y));
textView.setX(x);
textView.setY(y);
//change the text position here
this.sendEmptyMessageDelayed(0, 30000);
}
}
textView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// use any of your own colors here...
textView.setTextColor(android.R.color.holo_purple);
return true;
}
});
See also https://developer.android.com/reference/android/widget/TextView.html#setTextColor(int)

Categories