Hey, I'm MakyOnCover and please sorry my English!
I'm trying to make a Android Game in java, but I'm having problems with some kind of joystick I'm trying to denvelop!
The situation is this: the bitmap named joystick1 is not creating when I pressed the screen, so I would like to know why and how can I resolve this problem?
Thank you for your attention!
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.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
public class Class1 extends Activity implements OnTouchListener{
/** Called when the activity is first created. */
GameView a;
boolean toque;
float x, y, jposx, jposy;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
a = new GameView(this);
a.setOnTouchListener(this);
setContentView(new GameView(this));
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
x = event.getX();
y = event.getY();
return false;
}
public class GameView extends SurfaceView implements Runnable{
private Bitmap joystick1,joystick2;
private Bitmap shot = BitmapFactory.decodeResource(getResources(),R.drawable.shot);
Class1 e;
SurfaceHolder a;
Thread thread1 = null;
boolean correr = true;
public GameView(Context context){
super (context);
a = getHolder();
thread1 = new Thread(this);
thread1.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
while(correr){
if(!a.getSurface().isValid())
continue;
Canvas canvas = a.lockCanvas();
joystick2 = BitmapFactory.decodeResource(getResources(),R.drawable.joystick2);
canvas.drawBitmap(joystick2,16,16,null);
if (x != 0 && y != 0){
joystick1 = BitmapFactory.decodeResource(getResources(),R.drawable.joystick1);
canvas.drawBitmap(joystick1,x,y,null);
}
canvas.drawBitmap(shot,0 + 20,canvas.getHeight() - shot.getHeight() - 18,null);
a.unlockCanvasAndPost(canvas);
}
}
}
}
Today i decided to learn to code using eclipse and the andriod skd (2.3.3), I'm trying to code a basic soundboard and its not coming up with errors but the sounds are still not playing. If anyone could look at the code and give me a hand that would be great
Code:
package com.mkyong.android;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class AppActivity extends Activity {
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(context, App2Activity.class);
startActivity(intent);
}
});
}
public class PlayIt extends Activity implements OnClickListener {
MediaPlayer mp1;
MediaPlayer mp2;
public void onCreate1(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mp1 = MediaPlayer.create(this, R.raw.froze);
mp2 = MediaPlayer.create(this, R.raw.lasagna);
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener((OnClickListener) this);
final Button button = (Button) findViewById(R.id.button02);
button.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
mp1.start();
break;
case R.id.button02:
mp2.start();
break;
}
}
@Override
protected void onDestroy() {
mp1.release();
mp2.release();
super.onDestroy();
}
}
}
i dont have any idea about any code
I have done a lot of searching and I have come up with this code to try and display images that are located in a Folder on my SDCard. The folder is located at /.data/ToDo/.nomedia/ (I am trying to hide this images from the Main Android Gallery) The Code seems to run fine, i don't get any errors, but it's just not displaying the images. I was hoping someone could tell me what I am missing. Any Help would be greatly appreciated!!
Here is my GalleryActivity
Code:
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
public class GalleryActivity extends Activity {
/** Called when the activity is first created. */
private Cursor imagecursor, actualimagecursor, cursor;
private int image_column_index, actual_image_column_index;
File sdCardDir = Environment.getExternalStorageDirectory(); //SDCard Location
String imagesDir = ("sdCardDir" + "/.data/ToDo/.nomedia/"); //Path to Images
GridView imagegrid;
private int count;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
init_phone_image_grid();
}
private void init_phone_image_grid() {
String[] img = { MediaStore.Images.Media._ID };
imagecursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, img, MediaStore.Images.Media.DATA + " like ? ", new String[] {imagesDir}, null);
image_column_index = imagecursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
count = imagecursor.getCount();
imagegrid = (GridView) findViewById(R.id.sdcard);
imagegrid.setAdapter(new ImageAdapter(getApplicationContext()));
imagegrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
System.gc();
String[] proj = { MediaStore.Images.Media.DATA };
actualimagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,null, null, null);
actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToPosition(position);
String i = actualimagecursor.getString(actual_image_column_index);
System.gc();
Intent intent = new Intent(getApplicationContext(), GalleryFlow.class);
intent.putExtra("filename", i);
startActivity(intent);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position,View convertView,ViewGroup parent) {
System.gc();
ImageView i = new ImageView(mContext.getApplicationContext());
if (convertView == null) {
imagecursor.moveToPosition(position);
int id = imagecursor.getInt(image_column_index);
int imageID = 0;
Uri uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID) );
String url = uri.toString();
// Set the content of the image based on the image URI
int originalImageId = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1, url.length()));
Bitmap b = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), originalImageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
//i.setImageURI(Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID)));
i.setImageBitmap(b);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
}
else {
i = (ImageView) convertView;
}
return i;
}
}
}
I made Instagram type application in Android Studio, but whenever I try to upload image in my app, it uploads to my profile picture. I checked my intents and they are really perfect. First file is GalleryFragment.java in which we will select the photo which we want to upload and Second file is NextActivity.java which is used to Share the image to profile. But in GalleryFragment.java I have intent getActivity() to NextActivity.java and AccountSettingsActivity.java in which we can change out profile picture. But whenever I click on Next it doesn't take me to NextActivity.java but to the AccountSettingsActivity.java and updates my profile picture. If there is Firebase error so tell me. And the same issue is occurred when I try to upload photo from camera inside the application and it doesn't do anything. I have posted 3 files.
GalleryFragment.java
Code:
package darthvader.com.pictagram.Share;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.ArrayList;
import java.util.Objects;
import darthvader.com.pictagram.Profile.AccountSettingsActivity;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.FilePaths;
import darthvader.com.pictagram.Utils.FileSearch;
import darthvader.com.pictagram.Utils.GridImageAdapter;
public class GalleryFragment extends Fragment {
private static final String TAG = "GalleryFragment";
//constants
private static final int NUM_GRID_COLUMNS = 3;
//widgets
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;
//vars
private ArrayList<String> directories;
private String mAppend = "file:/";
private String mSelectedImage;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
galleryImage = view.findViewById(R.id.galleryImageView);
gridView = view.findViewById(R.id.gridView);
directorySpinner = view.findViewById(R.id.spinnerDirectory);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: started.");
ImageView shareClose = view.findViewById(R.id.ivCloseShare);
shareClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the gallery fragment.");
Objects.requireNonNull(getActivity()).finish();
}
});
TextView nextScreen = view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
if(isRootTask()){
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
startActivity(intent);
}else{
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}
}
});
init();
return view;
}
private boolean isRootTask(){
return ((ShareActivity) getActivity()).getTask() == 0;
}
private void init(){
FilePaths filePaths = new FilePaths();
//check for other folders indide "/storage/emulated/0/pictures"
if (FileSearch.getDirectoryPaths(filePaths.PICTURES) != null) {
directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
}
directories.add(filePaths.CAMERA);
ArrayList<String> directoryNames = new ArrayList<>();
for (int i = 0; i < directories.size(); i++) {
Log.d(TAG, "init: directory: " + directories.get(i));
int index = directories.get(i).lastIndexOf("/");
String string = directories.get(i).substring(index);
directoryNames.add(string);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
android.R.layout.simple_spinner_item, directoryNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected: " + directories.get(position));
//setup our image grid for the directory chosen
setupGridView(directories.get(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setupGridView(String selectedDirectory){
Log.d(TAG, "setupGridView: directory chosen: " + selectedDirectory);
final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory);
//set the grid column width
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
//use the grid adapter to adapter the images to gridview
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, mAppend, imgURLs);
gridView.setAdapter(adapter);
//set the first image to be displayed when the activity fragment view is inflated
try{
setImage(imgURLs.get(0), galleryImage, mAppend);
mSelectedImage = imgURLs.get(0);
}catch (ArrayIndexOutOfBoundsException e){
Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " +e.getMessage() );
}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected an image: " + imgURLs.get(position));
setImage(imgURLs.get(position), galleryImage, mAppend);
mSelectedImage = imgURLs.get(position);
}
});
}
private void setImage(String imgURL, ImageView image, String append){
Log.d(TAG, "setImage: setting image");
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(append + imgURL, image, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
mProgressBar.setVisibility(View.INVISIBLE);
}
});
}
}
NextActivity.java
Code:
package darthvader.com.pictagram.Share;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.FirebaseMethods;
import darthvader.com.pictagram.Utils.UniversalImageLoader;
import darthvader.com.pictagram.models.User;
public class NextActivity extends AppCompatActivity {
private static final String TAG = "NextActivity";
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
//widgets
private EditText mCaption;
//vars
private String mAppend = "file:/";
private int imageCount = 0;
private String imgUrl;
private Bitmap bitmap;
private Intent intent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
mFirebaseMethods = new FirebaseMethods(NextActivity.this);
mCaption = findViewById(R.id.caption);
setupFirebaseAuth();
ImageView backArrow = findViewById(R.id.ivBackArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the activity");
finish();
}
});
TextView share = findViewById(R.id.tvShare);
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
//upload the image to firebase
Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
String caption = mCaption.getText().toString();
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl,null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = intent.getParcelableExtra(getString(R.string.selected_bitmap));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null,bitmap);
}
}
});
setImage();
}
private void someMethod(){
/*
Step 1)
Create a data model for Photos
Step 2)
Add properties to the Photo Objects (caption, date, imageUrl, photo_id, tags, user_id)
Step 3)
Count the number of photos that the user already has.
Step 4)
a) Upload the photo to Firebase Storage
b) insert into 'photos' node
c) insert into 'user_photos' node
*/
}
/**
* gets the image url from the incoming intent and displays the chosen image
*/
private void setImage(){
intent = getIntent();
ImageView image = findViewById(R.id.imageShare);
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
Log.d(TAG, "setImage: got new image url: " + imgUrl);
UniversalImageLoader.setImage(imgUrl, image, null, mAppend);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = intent.getParcelableExtra(getString(R.string.selected_bitmap));
Log.d(TAG, "setImage: got new bitmap");
image.setImageBitmap(bitmap);
}
}
/*
------------------------------------ Firebase ---------------------------------------------
*/
/**
* Setup the firebase auth object
*/
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
Log.d(TAG, "onDataChange: image count: " + imageCount);
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
imageCount = mFirebaseMethods.getImageCount(dataSnapshot);
Log.d(TAG, "onDataChange: image count: " + imageCount);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
PhotoFragment.java
Code:
package darthvader.com.pictagram.Share;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import java.util.Objects;
import darthvader.com.pictagram.Profile.AccountSettingsActivity;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.Permissions;
public class PhotoFragment extends Fragment {
private static final String TAG = "PhotoFragment";
//constant
private static final int PHOTO_FRAGMENT_NUM = 1;
private static final int GALLERY_FRAGMENT_NUM = 2;
private static final int CAMERA_REQUEST_CODE = 5;
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_photo, container, false);
Log.d(TAG, "onCreateView: started.");
Button btnLaunchCamera = (Button) view.findViewById(R.id.btnLaunchCamera);
btnLaunchCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: launching camera.");
if(((ShareActivity)getActivity()).getCurrentTabNumber() == PHOTO_FRAGMENT_NUM){
if(((ShareActivity)getActivity()).checkPermissions(Permissions.CAMERA_PERMISSION[0])){
Log.d(TAG, "onClick: starting camera");
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}else{
Intent intent = new Intent(getActivity(), ShareActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
});
return view;
}
private boolean isRootTask(){
if(((ShareActivity)getActivity()).getTask() == 0){
return true;
}
else{
return false;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE){
Log.d(TAG, "onActivityResult: done taking a photo.");
Log.d(TAG, "onActivityResult: attempting to navigate to final share screen.");
Bitmap bitmap;
bitmap = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
if(isRootTask()){
try{
Log.d(TAG, "onActivityResult: received new bitmap from camera: " + bitmap);
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
startActivity(intent);
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException: " + e.getMessage());
}
}else{
try{
Log.d(TAG, "onActivityResult: received new bitmap from camera: " + bitmap);
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException: " + e.getMessage());
}
}
}
}
}
In the following code drawing using DrawView works for me. But I want to draw a shape on touching the canvas. MyView is supposed to do that, but how to get it working?
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.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends Activity {
DrawView drawView;
MyView myView;
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
myView = new MyView(this);
myView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
paint.setColor(Color.BLACK);
}
@override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(10, 20, 30, 40, paint);
canvas.drawLine(20, 10, 50, 20, paint);
}
}
class MyView extends View {
private float xDown = 0,yDown = 0, xUp = 0, yUp = 0;
Paint mPaint;
boolean touched = false;
public MyView(Context context) {
super(context);
init(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
mPaint = new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.STROKE);
}
@override
protected void onDraw (Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT);
if(touched) {
canvas.drawRect(xDown, yDown, xUp, yUp, mPaint);
}
}
@override
public boolean onTouchEvent (MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
xDown = event.getX();
yDown = event.getY();
xUp = 0;
yUp = 0;
break;
case MotionEvent.ACTION_MOVE:
xUp = event.getX();
yUp = event.getY();
touched = true;
break;
case MotionEvent.ACTION_UP:
xUp = event.getX();
yUp = event.getY();
touched = true;
break;
}
invalidate();
return true;
}
}
}
The second
BjornAndroid said:
setContentView(drawView);
Click to expand...
Click to collapse
had to be
setContentView(myView);