Hey :) I have a code of a ball that using the motion sensor and I want to make my app count time and when you lose, save this time for a record, so I did it, but my problem is, I can't extend my fragment layout, here is my full code:
package com.example.theball;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
#SuppressLint("NewApi") public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
#SuppressWarnings("unused")
private long lastUpdate;
AnimatedView animatedView = null;
ShapeDrawable mDrawable = new ShapeDrawable();
public static int x;
public static int y;
public static final int width = 50;
public static final int height = 50;
public boolean firstDraw = true;
private int screen_width;
private int screen_height;
private int sensorX;
private Timer t;
private int TimeCounter = 0;
private int sensorY;
private static int score = 0;
private static SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
lastUpdate = System.currentTimeMillis();
animatedView = new AnimatedView(this);
setContentView(animatedView);
t=new Timer();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
TimeCounter++;
}
});
}
}, 0, 1000);
}
public static class MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
TextView highscore_int = (TextView)v.findViewById(R.id.highscore_int );
score = prefs.getInt("key", 0);
highscore_int.setText("Highscore:" + score +" seconds.");
return v;
}
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
sensorY = (int) event.values[1];
sensorX = (int) event.values[0];
x -= sensorX*3;
y += sensorY*3;
if(x <= 0 || x >= screen_width || y <= 0 || y >= screen_height) {
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int oldScore = prefs.getInt("key", 0);
if( TimeCounter > oldScore ){
Editor edit = prefs.edit();
edit.putInt("key", TimeCounter);
edit.commit(); }
Intent myIntent = new Intent(this, YouLost.class);
startActivity(myIntent);
}
}
}
public class AnimatedView extends ImageView {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
static final int width = 50;
static final int height = 50;
#SuppressLint("NewApi")
public AnimatedView(Context context) {
super(context);
// TODO Auto-generated constructor stub
display.getSize(size);
screen_width = size.x;
screen_height = size.y;
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xffffAC23);
mDrawable.setBounds(0, 0, screen_width, screen_height);
}
#Override
protected void onDraw(Canvas canvas) {
mDrawable.setBounds(x, y, x + width, y + height);
if(firstDraw) {
x = screen_width / 2;
y = screen_height / 2;
firstDraw = false;
}
mDrawable.draw(canvas);
invalidate();
}
}
}
XML FILE:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/highscore_int"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginTop="0dp"
android:layout_weight="0.14"
android:text="12312312"
android:textColor="#android:color/black"
android:textSize="40sp" />
</LinearLayout>
I can't see the highscore_int on my device, only at the eclipse xml file grahpic layout.
You have defined MainActivity twice. Rename the second one to e.g. MainFragment (or something else) and you should be fine.
But I would also recommend to move the Fragment to a different file as well.
Related
I want to make android app like the following site.
https://sectional-anatomy.org/ct-abdomen/ or like https://radiopaedia.org/cases/squamous-cell-carcinoma-oral-cavity
There are multiple pictures and these are changing by scrolling.
I have done something like that with imageswitcher and onTouch event with action_down and action_up but it doesn't work because when I remove my finger then it goes to the first image it doesn't stay where I left.
Here is my code:
package com.radiology.radiologymenu.tomografi;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import com.radiology.radiologymenu.R;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class ImageChangeActivity extends AppCompatActivity {
private ImageSwitcher imageSwitcher;
private ImageView box;
// Size
private int frameHeight;
private int boxSize;
private int screenHeight;
// Position
private int boxY;
// Speed
private int boxSpeed;
// Score
private int score = 0;
// Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();
// Status Check
private boolean action_flg = false;
private boolean start_flg = false;
private String pic;
private ArrayList<Integer> slidePictures;
private static final Integer[] image= {
R.drawable.sagittal_boyun_1, R.drawable.sagittal_boyun_2, R.drawable.sagittal_boyun_3, R.drawable.sagittal_boyun_4,
R.drawable.sagittal_boyun_5, R.drawable.sagittal_boyun_6, R.drawable.sagittal_boyun_7, R.drawable.sagittal_boyun_8,
R.drawable.sagittal_boyun_9, R.drawable.sagittal_boyun_10, R.drawable.sagittal_boyun_11,
R.drawable.sagittal_boyun_12, R.drawable.sagittal_boyun_13, R.drawable.sagittal_boyun_14, R.drawable.sagittal_boyun_15,
R.drawable.sagittal_boyun_16, R.drawable.sagittal_boyun_17, R.drawable.sagittal_boyun_18, R.drawable.sagittal_boyun_19,
R.drawable.sagittal_boyun_20, R.drawable.sagittal_boyun_21, R.drawable.sagittal_boyun_22, R.drawable.sagittal_boyun_23,
R.drawable.sagittal_boyun_24, R.drawable.sagittal_boyun_25, R.drawable.sagittal_boyun_26, R.drawable.sagittal_boyun_27,
R.drawable.sagittal_boyun_28, R.drawable.sagittal_boyun_29, R.drawable.sagittal_boyun_30, R.drawable.sagittal_boyun_31,
R.drawable.sagittal_boyun_32, R.drawable.sagittal_boyun_33, R.drawable.sagittal_boyun_34, R.drawable.sagittal_boyun_35,
R.drawable.sagittal_boyun_36, R.drawable.sagittal_boyun_37, R.drawable.sagittal_boyun_38, R.drawable.sagittal_boyun_39,
R.drawable.sagittal_boyun_40, R.drawable.sagittal_boyun_41, R.drawable.sagittal_boyun_42, R.drawable.sagittal_boyun_43,
R.drawable.sagittal_boyun_44, R.drawable.sagittal_boyun_45 };
int i = 0;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_activity_main);
pic = getIntent().getExtras().getString("pic");
slidePictures = (ArrayList<Integer>) getIntent().getExtras().getSerializable("slidePictures");
getView2(pic,slidePictures);
}
public void getView2(String strings, ArrayList<Integer> slidePictures){
setContentView(R.layout.slide_activity_main);
TextView textView = (TextView) findViewById(R.id.resimText);
textView.setText(strings.toString());
imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
box = (ImageView) findViewById(R.id.box);
// Get screen size.
WindowManager wm = getWindowManager();
Display disp = wm.getDefaultDisplay();
Point size = new Point();
disp.getSize(size);
screenHeight = size.y;
boxSpeed = Math.round(screenHeight / 60); // 1280 / 60 = 21.333... => 21
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
#Override
public View makeView() {
ImageView imageView = new ImageView(getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
FrameLayout.LayoutParams params = new ImageSwitcher.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(params);
return imageView;
}
});
imageSwitcher.setImageResource(slidePictures.get(0));
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
finish();
}
return super.onKeyDown(keyCode, event);
}
public void changePos() {
// Move Box
if (action_flg == true) {
// Touching
boxY -= boxSpeed;
if (i<slidePictures.size()-1){
i++;
imageSwitcher.setImageResource(slidePictures.get(i));
}
} else {
// Releasing
boxY += boxSpeed;
if (i>0){
i--;
imageSwitcher.setImageResource(slidePictures.get(i));
}
}
// Check box position.
if (boxY < 0) boxY = 0;
if (boxY > frameHeight - boxSize) boxY = frameHeight - boxSize;
box.setY(boxY);
}
public boolean onTouchEvent(MotionEvent me) {
if (start_flg == false) {
start_flg = true;
// Why get frame height and box height here?
// Because the UI has not been set on the screen in OnCreate()!!
FrameLayout frame = (FrameLayout) findViewById(R.id.frame);
frameHeight = frame.getHeight();
boxY = (int)box.getY();
// The box is a square.(height and width are the same.)
boxSize = box.getHeight();
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
changePos();
}
});
}
}, 0, 40);
} else {
if (me.getAction() == MotionEvent.ACTION_DOWN) {
action_flg = false;
} else if (me.getAction() == MotionEvent.ACTION_UP) {
action_flg = true;
}
}
return true;
}
}
This SensorTestActivity.java in which Android Studio marks R in red:
package szabojanos.accelerometer;
import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class SensorTestActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private boolean color = false;
private View view;
private long lastUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = findViewById(R.id.textview);
view.setBackgroundColor(Color.GREEN);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
}
}
private void getAccelerometer(SensorEvent event) {
float[] values = event.values;
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = event.timestamp;
if (accelationSquareRoot >= 2) //
{
if (actualTime - lastUpdate < 200) {
return;
}
lastUpdate = actualTime;
Toast.makeText(this, "Az eszköz fel volt rázva", Toast.LENGTH_SHORT)
.show();
if (color) {
view.setBackgroundColor(Color.GREEN);
} else {
view.setBackgroundColor(Color.RED);
}
color = !color;
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
And this is android_sensor_test.xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
I was following this Tutorial: http://www.vogella.com/tutorials/AndroidSensor/article.html#tutorial-accelerometer
Any help would be appreciated.
Clean-Rebuild Your project at first and then Import R
Basic Syntax
import szabojanos.accelerometer.R;
FYI
Call requestWindowFeature after super.onCreate.
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);// Call this after super.onCreate
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
You are missing the .R import. You could auto fix this by going on the red line and press the combination ALT+ENTER and choose import yourpackage.R
import yourpackage.R and if there is any issues in youe xml file please resolve then try to clean and build.
I have this android project, can not identify why it is eating up RAM ? Note there is no processing just RAM being filled in. I have read Android RAM issues and how to solve, but can't make out what to do. I am new to both android and java.
Noticed just now (in Android Monitor - RAM) my app is using only 4MB of memory.
If anyone tries to run (please do - MainActivity is launcher and MyCanvas is just a class used as View) this, i can use speed variable as high as 100 (even more maybe), make thread call back in 10ms or even more frequent - it creates no problem. But as soon as I touch and move garbage collector comes pauses everything.
MyCanvas.java (used as view)
package com.abc.mygraphics;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
import java.util.Random;
import android.os.Handler;
public class MyCanvas extends View {
public static Paint paint;
//public static int n = 5000;
public static int N = 100, particleSize = 3;
public static int height, width;
public static float[][] pos = new float[N][2];
public static float[][] pos0 = new float[N][2];
//public static float distX, distY, dist;
Handler handler = new Handler();
public static int speed = 1;
public static int gravityX, gravityY;
public static Random random = new Random();
public static int[] colorList = new int[10];
public static int sphereSize = 100, M = 10;
public static float[] distance = new float[N];
public static int[][] gravity = new int[N][2];
public static boolean[] direction = new boolean[N];
public static int[] moved = new int[N];
public MyCanvas(Context context) {
super(context);
width = MainActivity.sharedPreferences.getInt("screenX", 200);
height = MainActivity.sharedPreferences.getInt("screenY", 200);
colorList = new int[]{Color.RED, 0xffff4000, 0xffffff00, 0xff40ff00, 0xff00ff00, 0xff00ff80, 0xff0080ff, 0xff0000ff, 0xffbf00ff, 0xffff0040};
paint = new Paint();
paint.setColor(Color.GRAY);
int i;
for (i = 0; i < N; i++) {
pos[i][0] = random.nextInt(width);
pos[i][1] = random.nextInt(height);
pos0[i][0] = pos[i][0];
pos0[i][1] = pos[i][1];
moved[i] = 0;
direction[i] = true;
}
final Runnable r = new Runnable() {
public void run() {
invalidate();
handler.postDelayed(this, 100);
}
};
handler.postDelayed(r, 100);
}
public static void changeGravity(){
gravityX = MainActivity.sharedPreferences.getInt("x",200);
gravityY = MainActivity.sharedPreferences.getInt("y",200);
// gravityY -= 68;
for(int i=0;i<N;i++){
calcDist(i);
}
}
#Override
public void onDraw(Canvas canvas){
int i;
int x; //remove at some poitnt
canvas.drawColor(Color.BLACK);
//canvas.drawCircle(gravityX,gravityY, 50, paint);
for(i=0;i<N;i++) {
setPosition(i);
x = random.nextInt(10);
paint.setColor(colorList[x]);
canvas.drawCircle(pos[i][0], pos[i][1], particleSize, paint);
}
}
public static void setPosition(int i){
// this is wrong
if(moved[i] >= (int)distance[i]/speed){
direction[i] = !direction[i];
setGravity(i);
}
else{
pos[i][0] = pos0[i][0] + speed*moved[i]*(gravity[i][0]- pos0[i][0])/distance[i];
pos[i][1] = pos0[i][1] + speed*moved[i]*(gravity[i][1]- pos0[i][1])/distance[i];
moved[i]++;
}
}
public static void calcDist(int i){
setGravity(i);
distance[i] = (float) Math.sqrt( Math.pow((gravity[i][0]-pos[i][0]),2) + Math.pow((gravity[i][1]-pos[i][1]),2) );
}
public static void setGravity(int i){
// do not forget to set pos0 in both cases
if(direction[i]){
gravity[i][0] = gravityX;
gravity[i][1] = gravityY;
}
else{
// make this biased on radius of sphere
gravity[i][0] = random.nextInt(width);
gravity[i][1] = random.nextInt(height);
}
pos0[i][0] = pos[i][0];
pos0[i][1] = pos[i][1];
moved[i]=0;
}
}
Main Activity.java
package com.abc.mygraphics;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import com.abc.mygraphics.MyCanvas;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
//DrawingView dr = new DrawingView(this);
public static SharedPreferences sharedPreferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
sharedPreferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("screenX",width);
editor.putInt("screenY", height);
editor.putInt("x", 200);
editor.putInt("y", 200);
editor.commit();
setContentView(new MyCanvas(this));
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// int x = (int)event.getX();
//int y = (int)event.getY();
int x = (int) event.getRawX();
int y = (int) event.getRawY();
//sharedPreferences = getSharedPreferences("CheckSharing",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("x", x);
editor.putInt("y", y);
editor.apply();
MyCanvas.changeGravity();
return false;
}
}
Got my problem.
I was trying to call my methods every time a touch event happens, this is something we can't do because when you drag your mouse there are literally thousands(possibly more) touch events happening.
Try understanding from code. In main activity we have our onTouch event listener which calls changeGravity() method which in turn calls calcDist() and setGravity() (from calcDist() ) . So thats a lot of garbage being generated and hence the GC comes in to play, it pauses the application and everything seems like hanged.
Solution - Just place the calcDist() call inside thread, so whatever be the vakue of gravity will come in effect in 10ms. This is something our emulator and phone are capable of, compared to what happens if we call from changeGravity() method.
I have developed an Application , which uses screen as a Slate and finger as a Chalk, which is working properly. But I want to use different color types for chalk.
Here is my Code:
MyDemo.java
package com.example.mydemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MyDemo extends Activity {
private LinearLayout root;
private Button btnReset;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_demo);
root = (LinearLayout) findViewById(R.id.root);
btnReset = (Button) findViewById(R.id.reset);
final MyImageView view = new MyImageView(this);
view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
root.addView(view);
btnReset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
view.reset();
}
});
}
}
MyImageView.java
package com.example.mydemo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class MyImageView extends ImageView implements View.OnTouchListener {
private int id = -1;
private Path path;
private List<Path> paths = new ArrayList<Path>();
private List<PointF> points = new ArrayList<PointF>();
boolean multiTouch = false;
public MyImageView(Context context) {
super(context);
this.setOnTouchListener(this);
}
public void reset() {
paths.clear();
points.clear();
path = null;
id = -1;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = createPen(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
for (Path path : paths) {
canvas.drawPath(path, paint);
}
for (int i = 0; i < points.size(); i++) {
PointF p = points.get(i);
canvas.drawText("" + p.x, p.y, i, createPen(Color.WHITE));
}
}
private PointF copy(PointF p) {
PointF copy = new PointF();
copy.set(p);
return copy;
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
multiTouch = false;
id = event.getPointerId(0);
PointF p = getPoint(event, id);
path = new Path();
path.moveTo(p.x, p.y);
paths.add(path);
points.add(copy(p));
break;
case MotionEvent.ACTION_POINTER_DOWN:
multiTouch = true;
for (int i = 0; i < event.getPointerCount(); i++) {
int tId = event.getPointerId(i);
if (tId != id) {
points.add(getPoint(event,i));
}
}
break;
case MotionEvent.ACTION_MOVE:
if (!multiTouch) {
p =getPoint(event, id);
path.lineTo(p.x, p.y);
}
break;
}
invalidate();
return true;
}
private PointF getPoint(MotionEvent event, int i) {
int index = 0;
return new PointF(event.getX(index), event.getY(index));
}
private Paint createPen(int color) {
Paint pen = new Paint();
pen.setColor(color);
float width = 3;
pen.setStrokeWidth(width);
return pen;
}
}
activity_my_demo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/root" xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:id="#+id/reset" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
/>
</LinearLayout>
Can any one tell me what should be added or changed in my code so that I can use different colors for Chalk?
You can take the sample in your android folder's..
For the color picker go to in this folder:
android/samples/android-YOURS_VERSION/ApiDemos
Use this, review this code. than your problem will be solve
package com.example.changecolor;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity
implements View.OnClickListener, UberColorPickerDialog.OnColorChangedListener {
private int mColor = 0xFFFF0000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Write the version number
PackageManager pm = getPackageManager();
String versionName = "";
try {
PackageInfo pi = pm.getPackageInfo("com.keithwiley.android.ubercolorpickerdemo", 0);
versionName = pi.versionName;
}
catch (Exception e) {
}
TextView textView = (TextView) findViewById(R.id.version);
textView.setText(versionName);
//Initialize the sample
((LinearLayout) findViewById(R.id.LinearLayout)).setBackgroundColor(mColor);
float hsv[] = new float[3];
Color.colorToHSV(mColor, hsv);
if (UberColorPickerDialog.isGray(mColor))
hsv[1] = 0;
if (hsv[2] < .5)
((TextView) findViewById(R.id.sample)).setTextColor(Color.WHITE);
else ((TextView) findViewById(R.id.sample)).setTextColor(Color.BLACK);
//Set up the buttons
Button button = (Button) findViewById(R.id.colorPickerWithTitle);
button.setOnClickListener(this);
button = (Button) findViewById(R.id.colorPickerWithToast);
button.setOnClickListener(this);
}
protected void onPause() {
super.onPause();
}
protected void onResume() {
super.onResume();
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return true;
}
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
}
return super.onOptionsItemSelected(item);
}
public void onClick(View v) {
if (v.getId() == R.id.colorPickerWithTitle)
new UberColorPickerDialog(this, this, mColor, true).show();
if (v.getId() == R.id.colorPickerWithToast)
new UberColorPickerDialog(this, this, mColor, false).show();
}
public void colorChanged(int color) {
((LinearLayout) findViewById(R.id.LinearLayout)).setBackgroundColor(mColor=color);
float hsv[] = new float[3];
Color.colorToHSV(mColor, hsv);
//if (UberColorPickerDialog.isGray(mColor))
// hsv[1] = 0;
if (hsv[2] < .5)
((TextView) findViewById(R.id.sample)).setTextColor(Color.WHITE);
else ((TextView) findViewById(R.id.sample)).setTextColor(Color.BLACK);
}
}
And use the color picker class
Hello EclipeE wants to initialise:
CustomDrawableView mCustomDrawableView;
Any ideas?
Cheers
Phil
Here's my code:
package com.android.phil.graphtoggle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
public class MainActivity extends Activity
{
public int graph_toggle = 0;
public int data_toggle=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageButton graph_toggle_button = (ImageButton) findViewById(R.id.graph_toggle);
final ImageButton graph_settings_button = (ImageButton) findViewById(R.id.graph_type);
final ImageButton data_toggle_button = (ImageButton) findViewById(R.id.data_toggle);
CustomDrawableView mCustomDrawableView;
RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.relativeLayout1);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,200);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
// add here other layout params rules to make your
// custom view stay below the buttons
mCustomDrawableView.setLayoutParams(lp);
mainLayout.addView(mCustomDrawableView);
graph_toggle_button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
if (graph_toggle==2)
{
graph_toggle=0;
}
else
{
graph_toggle++;
}
if (graph_toggle==0)
{
graph_settings_button.setImageResource(R.drawable.close);
}
if (graph_toggle==1)
{
graph_settings_button.setImageResource(R.drawable.ohlc_bars);
}
if(graph_toggle==2)
{
graph_settings_button.setImageResource(R.drawable.candles);
}
}
});
data_toggle_button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
if (data_toggle==2)
{
data_toggle=0;
}
else
{
data_toggle++;
}
if (data_toggle==0)
{
data_toggle_button.setImageResource(R.drawable.ohlc_bars_daily);
}
if (data_toggle==1)
{
data_toggle_button.setImageResource(R.drawable.ohlc_bars_weekly);
}
if(data_toggle==2)
{
data_toggle_button.setImageResource(R.drawable.ohlc_bars_monthly);
}
}
});
}
public class CustomDrawableView extends View
{
private ShapeDrawable mDrawable;
public CustomDrawableView(Context context)
{
super(context);
int x = 10;
int y = 100;
int width = 300;
int height = 50;
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xff74AC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
protected void onDraw(Canvas canvas)
{
mDrawable.draw(canvas);
}
}
}
You aren't initializing mCustomDrawableView anywhere so mCustomDrawableView.setLayoutParams(lp); is going to cause a NullPointerException.
You are missing something like
mCustomDrawableView = (CustomDrawableView) this.findViewById(R.id.my_custom_view);