How to change the image of a ImageView from DialogFragment - android

So basically i have a Fragment class where i have a ImageView, where i have not set any image yet. So i want to do this from a Dialog Box where i have list and on the click of any of the items to add the image in the Fragment where the ImageView is situated. The image is a rectangle made in a xml file. If i add it from it's class the Fragment class it works. But i need it to add it from the Dialog Box.
And i tried this all day and nothing works, all that i get is nullPointerException in the same place where i try to call the add of the image in all the way i tried.
here is the code that i have got to after i tried a lot :).
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.ImageView;
public class BrickMessageBoxGreen extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.dialog_title_green);
builder.setItems(R.array.greenBricks_array,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
Arkitektur ark = new Arkitektur();
ImageView img = (ImageView)ark.getView().findViewById(R.id.green_brick);
ark.addGreenBrick(img);
}
});
return builder.create();
}
}
And here is the class where i have the ImageView:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnDragListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class Arkitektur extends Fragment implements OnTouchListener, OnDragListener {
private int _xDelta;
private int _yDelta;
ViewGroup _root;
private View arkitektur;
ImageView greenBrick;
ImageView redBrick;
ImageView yellowBrick;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
arkitektur = inflater.inflate(R.layout.arkitektur, container, false);
//arkitektur.findViewById(R.id.green_brick).setOnTouchListener(this);
//greenBrick = (ImageView) arkitektur.findViewById(R.id.green_brick);
//arkitektur.findViewById(R.id.root).setOnDragListener(this);
//arkitektur.findViewById(R.id.bottom_container).setOnDragListener(this);
//addGreenBrick();
_root = (ViewGroup) arkitektur.findViewById(R.id.root);
_root.setOnDragListener(this);
return arkitektur;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
final int X = (int) event.getRawX()*2;
final int Y = (int) event.getRawY()*2;
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
// layoutParams.rightMargin = -250;
// layoutParams.bottomMargin = -250;
v.setLayoutParams(layoutParams);
break;
}
_root.invalidate();
return true;
}
#Override
public boolean onDrag(View v, DragEvent e) {
if (e.getAction()==DragEvent.ACTION_DROP) {
View view = (View) e.getLocalState();
ViewGroup from = (ViewGroup) view.getParent();
from.removeView(view);
LinearLayout to = (LinearLayout) v;
to.addView(view);
view.setVisibility(View.VISIBLE);
}
return true;
}
public void addGreenBrick(View v)
{
v.findViewById(R.id.green_brick).setOnTouchListener(this);
greenBrick = (ImageView) v.findViewById(R.id.green_brick);
greenBrick.setImageResource(R.drawable.green_brick);
}
}
Thanks!

I agree with Tamilselvan Kalimuthu, just let your fragment implement a listener and set it as an attribute of BrickMessageBoxGreen class.
Edit:
Added some code to clarify the idea.
BrickMessageBoxGreen class:
public OnClickDialogListener listener //Attribute of your class
public void setDialogListener(OnClickDialogListener l){ //Setting the listener
this.listener = l;
}
new DialogInterface.OnClickListener() { //Changing onClick method
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
this.listener.onDialogClicked("green");
}
});
Arkitektur class:
public interface OnClickDialogListener { //Your listener definition, you could place it elsewhere
void onDialogClicked(String colorName);
}
public class Arkitektur extends Fragment implements OnTouchListener, OnDragListener, OnClickDialogListener { //Implementing your listener interface
public void onDialogClicked(String colorName){//Method implementation
if(colorName.equals("green")){
addGreenBrick();
}else if(colorName.equals("red")){
addRedBrick();
}else if(colorName.equals("yellor")){
addYellowBrick();
}
}

Related

How to start popupwindow from service in android?

I wish to create a floating button which will hover over the entire Android screen. When the button or hovering icon is clicked, it should open a small popupwindow.
I was able to create the hovering icon using service class however I am unable to launch popupwindow. Whenever I click the floating icon, the error log says:
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow;
/**
* Created by sejal on 17-Oct-15.
*/
public class bubble extends Service{
PopupWindow popw;
private WindowManager windowManager;
private ImageView floatingFaceBubble;
public void onCreate() {
super.onCreate();
floatingFaceBubble = new ImageView(this);
//a face floating bubble as imageView
floatingFaceBubble.setImageResource(R.drawable.bubble);
windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
//here is all the science of params
final LayoutParams myParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,
LayoutParams.TYPE_PHONE,
LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
myParams.gravity = Gravity.TOP | Gravity.LEFT;
myParams.x=0;
// add a floatingfacebubble icon in window
windowManager.addView(floatingFaceBubble, myParams);
try{
floatingFaceBubble.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getpopuppwindow();
}
});
//for moving the picture on touch and slide
floatingFaceBubble.setOnTouchListener(new View.OnTouchListener() {
LayoutParams paramsT = myParams;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
private long touchStartTime = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
//remove face bubble on long press
/* if(System.currentTimeMillis()-touchStartTime> ViewConfiguration.getLongPressTimeout() && initialTouchX== event.getX()){
//// windowManager.removeView(floatingFaceBubble);
//// stopSelf();
// return false;
// } */
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
touchStartTime = System.currentTimeMillis();
initialX = myParams.x;
initialY = myParams.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
myParams.x = initialX + (int) (event.getRawX() - initialTouchX);
myParams.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(v, myParams);
break;
}
return false;
}
});
} catch (Exception e){
e.printStackTrace();
}
}
//(ViewGroup) floatingFaceBubble.findViewById(R.id.pop)
private void getpopuppwindow() {
try {
System.out.print("111111");
LayoutInflater inflater = (LayoutInflater)bubble.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
System.out.print("222222");
View layout = inflater.inflate(R.layout.popup,(ViewGroup) floatingFaceBubble.findViewById(R.id.pop));
System.out.print("333333");
popw = new PopupWindow(layout ,300,100 ,true) ;
System.out.print("444444");
popw.showAtLocation(layout, Gravity.CENTER,0,0);
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
You should not do these ui operations in your service class. Because after you show your button service instance will be removed and there is no context when you click the button. I think you should follow similar approach like below.
Service Class:
Intent activityIntent = new Intent(context, MainActivity);
activityIntent.putExtra("showPopup", true);
context.startActivity(activityIntent);
Activity Class:
onCreate(){
boolean showPopUp = getIntent().getBooleanExtra("showPopup", false);
if(showPopUp){
// Show your popup here
}
}

AnimationDrawable into framelayout beside SurfaceView- Android

Hello all,
in my app, can i make an character (like, cartoon character...) to animate when i touch the screen?
i have another bitmaps (static not animated) on the screen.
i have all this character (10) bitmaps in all animation position (like a cartoon)
this is the code.. ( I NEED TO ANIMATE IT FOR EACH TOUCH )
`
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
public class Show extends Activity
{
private Bitmap imageOne;
private Bitmap imageTwo;
private Bitmap imageThree;
private List<Bitmap> images;
private ExplainView myView;
private AnimationDrawable animation;
private ImageView image;`
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(0x00000400, 0x00000400);
setContentView(R.layout.frame_layout);
image = new ImageView(this);
image.setBackgroundResource(R.drawable.tom_anim);
animation = (AnimationDrawable) rocketImage.getBackground();
images = new ArrayList<Bitmap>();
praper();
myView = new ExplainView(this,images,1); <------ this is the surface view class
FrameLayout fl = (FrameLayout)findViewById(R.id.frameLayout);
fl.addView(myView);
fl.addView(image);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
new Runnable() {
#Override
public void run() {
image.setVisibility(View.VISIBLE);
animation.stop();
animation.start();
}
};
}
return true;
}
private void praper()
{
imageOne = BitmapFactory.decodeResource(getResources(), R.drawable.trans_ar_alpha_1);
imageTwo = BitmapFactory.decodeResource(getResources(), R.drawable.trans_ar_alpha_2);
imageThree = BitmapFactory.decodeResource(getResources(), R.drawable.trans_ar_alpha_3);
images.add(0,imageOne);
images.add(1, imageTwo);
images.add(2, imageThree);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
if(hasFocus)
{
animation.start();
}
else
{
animation.stop();
}
}
}`
of course you can simply by using
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
x = arg1.getX();
y = arg1.getY();
switch(arg1.getAction())
{
case MotionEvent.ACTION_DOWN:
sx=arg1.getX();
sy = arg1.getY();
break;
case MotionEvent.ACTION_UP:
fx=arg1.getX();
fy = arg1.getY();
break;
}

How to create a button using onTouch?

I want to write a program which creates a button, whenever I'm touching the screen, the button should be created on the place where the screen was touched.
I wrote a program which creates circles, whenever and where the screen is touched, can anybody explain me how to make buttons instead of circles?
Thx.
Main Activity
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View.OnTouchListener;
public class SingleTouchActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SingleTouchEventView(this, null));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.single_touch, menu);
return true;
}
}
Touch Activity
import java.util.ArrayList; //not all imports are necessary
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.view.View.OnClickListener;
public class SingleTouchEventView extends RelativeLayout {
private Paint paint = new Paint();
List<Point> points = new ArrayList<Point>();
public SingleTouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE: // a pointer was moved
case MotionEvent.ACTION_UP:
Point p = new Point();
p.x = (int)event.getX();
p.y = (int)event.getY();
points.add(p);
Button button = new Button(getContext());
int buttonHeight = 50;
int buttonWidth = 50;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(buttonWidth, buttonHeight);
params.leftMargin = p.x;
params.topMargin = p.y;
addView(button, params);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
}
});
case MotionEvent.ACTION_CANCEL: {
break;
}
}
invalidate();
return true;
}
// Do something
}
First make your class extends a ViewGroup like RelativeLayout and FrameLayout in your case.
Then, on the touch event, create a Button (or a ImageView and setOnClickListener()), adjust the position of the button with margins on the view LayoutParams and add the button to the layout via addView().
Edit: The button creation will be like this on onTouchEvent():
Point p = new Point();
p.x = (int)event.getX();
p.y = (int)event.getY();
Button button = new Button(context);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(buttonWidth, buttonHeight);
params.leftMargin = p.x;
params.topMargin = p.y;
addView(button, params);
Also change this to be inside ACTION_UP to prevent creating multiple buttons on long pressing.
This is not possible. You can draw a circle because that is a graphic. If you were to make button appear then you would need to add it to XML. I assume you are making a game that requires elements to randomly appear. I suggest if this is the case to use and engine a spawn random circles and when touched do what you need. Hope this helps

How to Hide and Show Buttons on Alternate Touch Events

My activity displays images and i want to display two buttons when the user touch the screen, and to disappear these button on next touch.
My activity file ImageViewPager.java is as follows:
package com.pankajvatsa.testfeet;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class ImageViewPager extends Activity {
// Declare Variable
int position;
Button bWallpaperButton;
Button bDownloadButton;
RelativeLayout mainLay;
int flagForButton = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set title for the ViewPager
setTitle("ViewPager");
// Get the view from view_pager.xml
setContentView(R.layout.activity_image_view_pager);
mainLay = (RelativeLayout) findViewById(R.id.rl_view_pager);
mainLay.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
bWallpaperButton.setVisibility(View.VISIBLE);
bDownloadButton.setVisibility(View.VISIBLE);
return true;
}
if (event.getAction() == MotionEvent.ACTION_UP) {
bWallpaperButton.setVisibility(View.INVISIBLE);
bDownloadButton.setVisibility(View.INVISIBLE);
return true;
}
return true;
}
});
bWallpaperButton = (Button) findViewById(R.id.bSetWallpaper);
bDownloadButton = (Button) findViewById(R.id.bSaveToGallery);
// Retrieve data from MainActivity on item click event
Intent p = getIntent();
position = p.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
List<ImageView> images = new ArrayList<ImageView>();
// Retrieve all the images
for (int i = 0; i < imageAdapter.getCount(); i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(imageAdapter.mThumbIds[i]);
imageView.setScaleType(ImageView.ScaleType.CENTER);
images.add(imageView);
}
// Set the images into ViewPager
ImagePagerAdapter pageradapter = new ImagePagerAdapter(images);
ViewPager viewpager = (ViewPager) findViewById(R.id.image_pager);
viewpager.setAdapter(pageradapter);
// Show images following the position
viewpager.setCurrentItem(position);
}
}
And my xml file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true" >
<android.support.v4.view.ViewPager
android:id="#+id/image_pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true" >
</android.support.v4.view.ViewPager>
<Button
android:id="#+id/bSetWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="#string/set_wallpaper"
android:visibility="gone" />
<Button
android:id="#+id/bSaveToGallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="#string/save_local"
android:visibility="gone" />
</RelativeLayout>
Here is an example using LinearLayout but should work fine with RelativeLayout as well:
Button btn1;
boolean gone = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.button1);
LinearLayout ln = (LinearLayout)findViewById(R.id.LinearLayout01);
ln.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
if(!gone){
btn1.setVisibility(View.GONE);
gone = true;
}else{
btn1.setVisibility(View.VISIBLE);
gone = false;
}
}
return true;
}
});
}
Well, it somehow worked on removing the setOnTouchListener() from layout and adding it on the ViewPager.
My Updated code(with other changes for differentiating tap and swipe) is:
package com.pankajvatsa.testfeet;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class ImageViewPager extends Activity {
// Declare Variable
int position;
Button bWallpaperButton;
Button bDownloadButton;
RelativeLayout mainLay;
int flagForButton = 0;
boolean gone = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set title for the ViewPager
setTitle("ViewPager");
// Get the view from view_pager.xml
setContentView(R.layout.activity_image_view_pager);
bWallpaperButton = (Button) findViewById(R.id.bSetWallpaper);
bDownloadButton = (Button) findViewById(R.id.bSaveToGallery);
mainLay = (RelativeLayout) findViewById(R.id.rl_view_pager);
// Retrieve data from MainActivity on item click event
Intent p = getIntent();
position = p.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
List<ImageView> images = new ArrayList<ImageView>();
// Retrieve all the images
for (int i = 0; i < imageAdapter.getCount(); i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(imageAdapter.mThumbIds[i]);
imageView.setScaleType(ImageView.ScaleType.CENTER);
images.add(imageView);
}
// Set the images into ViewPager
ImagePagerAdapter pageradapter = new ImagePagerAdapter(images);
ViewPager viewpager = (ViewPager) findViewById(R.id.image_pager);
viewpager.setAdapter(pageradapter);
// Show images following the position
viewpager.setCurrentItem(position);
viewpager.setOnTouchListener(new View.OnTouchListener() {
private float pointX;
private float pointY;
private int tolerance = 50;
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
return false;
case MotionEvent.ACTION_DOWN:
pointX = event.getX();
pointY = event.getY();
break;
case MotionEvent.ACTION_UP:
boolean sameX = pointX + tolerance > event.getX() && pointX - tolerance < event.getX();
boolean sameY = pointY + tolerance > event.getY() && pointY - tolerance < event.getY();
if(sameX && sameY){
//The user "clicked" certain point in the screen or just returned to the same position an raised the finger
if(gone == false){
bWallpaperButton.setVisibility(View.GONE);
bDownloadButton.setVisibility(View.GONE);
gone = true;
}else{
bWallpaperButton.setVisibility(View.VISIBLE);
bDownloadButton.setVisibility(View.VISIBLE);
gone = false;
}
}
}
return false;
}
});
}
}

How to add Color Picker in Application?

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

Categories

Resources