Can't get OnTouchListner to work - java

I am trying to create my first android game (in eclipse) and I cannot seem to get OnTouchListner to work, mostly because I don't know how or where to create it. I am trying to figure out where someone taps the screen. Can someone please tell me how and where to create the OnTouchListner!
Activity class:
package com.gregsapps.fallingbird;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class Game extends Activity implements OnTouchListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.){
System.out.println("TOUCH");
}
return false;
}
}
View class:
package com.gregsapps.fallingbird;
import android.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;
public class GameView extends View{
private Bird bird;
private boolean runOnce = false;
private Context context;
public GameView(Context context) {
super(context);
this.context = context;
this.setDrawingCacheEnabled(true);
// TODO add setup code
}
protected void onDraw(Canvas canvas){
update(canvas);
//TODO add drawing code
this.buildDrawingCache();
//bird.canvasImage = this.getDrawingCache(true);
canvas.drawBitmap(bird.image, bird.x, bird.y, null);
System.out.println("drawing");
invalidate();
}
private void update(Canvas canvas){
//TODO add code to update stuff
if(runOnce == false){
bird = new Bird(canvas, com.gregsapps.fallingbird.R.drawable.bird, context);
runOnce = true;
}
bird.move();
}
}

Implement it like this :-
public class Game extends Activity implements OnTouchListener{
GameView gv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gv = new GameView(this);
setContentView(gv);
gv.setOnTouchListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = event.getX();
int y = event.getY();
System.out.println("Touched view at X: " + X + " Y: " + Y );
}
return false;
}
}

You should just be able to set it on the view you create:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GameView gv = new GameView(this);
setContentView(gv);
// set the touch listener for the view
gv.setOnTouchListener(this);
}

Related

How to set image as wall paper in viewpager app?

Edited code after following this link ...Set wallpaper from ViewPager .I developed simple viewpager app along with the background music. However, I want to modify my app so that image chosen by user will give them option to set as wallpaper....I don't want to implement any buttons in my app. User should be able to just touch the image , which will give them option to set as wallpaper...
I am getting error at this code curruntPosition=arg0;. It says "Current position cannot be resolve to a variable". I don't know what it mean ...
Following are my codes...
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
ViewPager viewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.start ();
viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
//Here you can set the wallpaper
curruntPosition=arg0;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause(){
super.onPause();
oursong.release();
oursong = null;
}
}
imageadapter.java
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
I just start with programming, so please give some explanations, or it will be great if you provide some codes .
First add this Permission to the Manifest
<uses-permission android:name="android.permission.SET_WALLPAPER">
Now for some code.
imageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(context);
try {
myWallpaperManager.setResource(GalImages[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Explantion : This will set that the Image will be clickable , when the image is clicked it will set the phone Wallpaper with the selected drawable.
getApplicationContext()
is the Context from the Activity.
This changes will take place inside the Adapter.
Activity
add this variable
int currentPosition;

Android: Constantly updating TextView with a new value

I need some suggestions as to how I can update a Textview located in the XML with a value generated through my code.
The program draws a straight line through the canvas, I want the textView to reflect the line's tip x-value.
My code as follows:
package com.example.threadexperiment1;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
lineDrawing InfiniteLine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InfiniteLine = new lineDrawing (this);
setContentView(R.layout.activity_main);
Thread thread = new Thread(InfiniteLine);
thread.start();
RelativeLayout RL1 = (RelativeLayout)findViewById(R.id.RelativeLayout1);
RL1.addView(InfiniteLine);
}
public class lineDrawing extends View implements Runnable {
float x=100, y=100;
Paint lineColour = new Paint ();
TextView TV1 = (TextView)findViewById(R.id.textView1);
//Constructor
public lineDrawing(Context context) {
super(context);
lineColour.setColor(Color.BLACK);
}
//ondraw codes
#Override
public void onDraw (Canvas canvas){
canvas.drawLine(0,0,x,y,lineColour);
if (x==500){
x=0;
y=0;
}
invalidate();
}
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(250);
}
catch (Exception e) {}
x+=10;
y+=10;
}
}
}
}
Try textView.setText(string) within the thread.

Android SeekBar extension

I have multiple Seek Bars on my activity (4) and for each there is a textView that suppose to show the progress of each SeekBar. I thought to extend the SeekBar Class and add to it's constructor a TextView Parameter so I can bind the two -> SeekBar and TextView . Here is my extended SeekBar class:
import android.content.Context;
import android.widget.SeekBar;
import android.widget.TextView;
public class SeekBarPlus extends SeekBar {
private TextView numberOfDrills;
public SeekBarPlus(Context context, TextView text) {
super(context);
// TODO Auto-generated constructor stub
numberOfDrills = (TextView) text;
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
numberOfDrills.setText(progress);
}
}
What is the Context option?
Now here is my MainActivity:
package com.simplemathgame;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import com.simplemathgame.SeekBarPlus;
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView numberOfAddDrills = (TextView) findViewById(R.id.add_drills_number);
TextView numberOfSubDrills = (TextView) findViewById(R.id.sub_drills_number);
TextView numberOfMulDrills = (TextView) findViewById(R.id.mul_drills_number);
TextView numberOfDivDrills = (TextView) findViewById(R.id.div_drills_number);
SeekBarPlus addSeekBar = SeekBarPlus((SeekBar) findViewById(R.id.add_seek_bar), numberOfAddDrills);
SeekBarPlus subSeekBar = SeekBarPlus((SeekBar) findViewById(R.id.sub_seek_bar), numberOfAddDrills);
SeekBarPlus mulSeekBar1 = SeekBarPlus((SeekBar) findViewById(R.id.mul_seek_bar), numberOfAddDrills);
SeekBarPlus divSeekBar1 = SeekBarPlus((SeekBar) findViewById(R.id.div_seek_bar), numberOfAddDrills);
}
}
I don't know how to it wright! Any suggestions would be appreciated!!!
try to use setter instead of constructor in your custom SeekBar:
public void setTextView(TextView text) {
numberOfDrills = text;
}
then in your activity, use
SeekBarPlus subSeekBar = (SeekBarPlus) findViewById(R.id.sub_seek_bar);
subSeekBar.setTextView(numberOfAddDrills);
you can also use normal Seekbar with OnSeekBarChangeListener:
SeekBar subSeekBar = (SeekBar) findViewById(R.id.sub_seek_bar);
subSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
numberOfDrills.setText(String.valueOf(progress));
}
});

How to add balloons in OpenStreetMap?

How do I add balloons like those on Google Maps (such as the one shown here) into OpenStreetMap? This is my OpenStreetMap code below:
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
public class MainActivity extends Activity {
MyItemizedOverlay myItemizedOverlay = null;
private MapController myMapController;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
myMapController = mapView.getController();
myMapController.setZoom(16);
Drawable marker=getResources().getDrawable(android.R.drawable.star_big_on);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
ResourceProxy resourceProxy = new
DefaultResourceProxyImpl(getApplicationContext());
myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
mapView.getOverlays().add(myItemizedOverlay);
GeoPoint myPoint1 = new GeoPoint(24.893379000000000000, 67.028060900000010000);
myItemizedOverlay.addItem(myPoint1, "myPoint1", "myPoint1");
GeoPoint myPoint2 = new GeoPoint(24.824796300000000000, 67.031565699999990000);
myItemizedOverlay.addItem(myPoint2, "myPoint2", "myPoint2");
}
}
import java.util.ArrayList;
import org.osmdroid.ResourceProxy;
import org.osmdroid.api.IMapView;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.overlay.ItemizedOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> overlayItemList = new ArrayList<OverlayItem>();
public MyItemizedOverlay(Drawable pDefaultMarker,
ResourceProxy pResourceProxy) {
super(pDefaultMarker, pResourceProxy);
// TODO Auto-generated constructor stub
}
public void addItem(GeoPoint p, String title, String snippet){
OverlayItem newItem = new OverlayItem(title, snippet, p);
overlayItemList.add(newItem);
populate();
}
#Override
public boolean onSnapToItem(int arg0, int arg1, Point arg2, IMapView arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
protected OverlayItem createItem(int arg0) {
// TODO Auto-generated method stub
return overlayItemList.get(arg0);
}
#Override
public int size() {
// TODO Auto-generated method stub
return overlayItemList.size();
}
}
I was with the same question and now I found a way:
Download the osmbonuspack here: https://code.google.com/p/osmbonuspack/
Follow this code:
ArrayList<ExtendedOverlayItem> overlayItemArray = new ArrayList<ExtendedOverlayItem>();
ExtendedOverlayItem item = new ExtendedOverlayItem("Title, "Description, new GeoPoint(Double latitude, Double longitude), this);
//creates a layer with ballons
ItemizedOverlayWithBubble<ExtendedOverlayItem> poiMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, overlayItemArray, mapView, new CustomMapInfoWindow(mapView));
// add the layer
mapView.getOverlays().add(poiMarkers);
Create a class called CustomMapInfoWindow:
import org.osmdroid.bonuspack.overlays.DefaultInfoWindow;
import org.osmdroid.bonuspack.overlays.ExtendedOverlayItem;
import org.osmdroid.views.MapView;
public class CustomMapInfoWindow extends DefaultInfoWindow {
public CustomMapInfoWindow(MapView mapView) {
super(R.layout.bonuspack_bubble, mapView);
}
#Override
public void onOpen(ExtendedOverlayItem item) {
super.onOpen(item);
}
}
Go to OSMBONUSPACKDEMO REPOSITORY and get bonuspack_bubble.xml and the drawables into drawable-mdpi folder.
You should take a look at the osmbonuspack library, which is an add-on for osmdroid. It includes an overlay that will display popup balloons:
https://code.google.com/p/osmbonuspack/

how to link the class shown below with main activity

here is the code of the class which i created which extends MainActivity and how can i call this from MainActivity?
I'm trying to figure out where I went wrong on referencing my surface view class, not my view. I only did the view as an example. Here is my main class:
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class SurfaceViewExample extends Activity implements OnTouchListener{
OurView v;
Bitmap ball;
float x,y;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
v=new OurView(this);
v.setOnTouchListener(this);
ball=BitmapFactory.decodeResource(getResources(),R.drawable.tennis_ball);
x = y = 0;
setContentView(v);
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
v.resume();
}
public class OurView extends SurfaceView implements Runnable{
Thread t;
SurfaceHolder holder;
boolean isItOk=false;
public OurView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder=getHolder();
}
public void run() {
// TODO Auto-generated method stub
while( isItOk ==true)
{
//drawing
if(holder.getSurface().isValid()) {
continue;
}
Canvas c=holder.lockCanvas();
c.drawARGB(255,150,150,10);
c.drawBitmap(ball, x+(ball.getWidth()/4), y+(ball.getHeight()), null);
holder.unlockCanvasAndPost(c);
}
}
public void pause()
{
isItOk=false;
while(true) {
try {
t.join();
}catch(InterruptedException e) {
e.printStackTrace();
}
break;
}
}
public void resume()
{
isItOk=true;
t=new Thread(this);
t.start();
}
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
The much i got is that you want to go SurfaceViewExample from your main activity for that you need to use intent on button click like
Intent i = new Intent(this, SurfaceViewExample.class);
startActivity(i) ;
and you have to add a permission in menifest to got to that activity like
<activity android:enabled="true" android:name="SurfaceViewExample" />
and you can see these links also
Calling one Activity from another in Android
http://developer.android.com/reference/android/content/Intent.html

Categories