Making canvas background as XML layout - android

I have an XML layout. I want to draw a line after getting the button clicked. I made an inner class to accomplish it. But when it do so my content view get changed to canvas of View class.
I want my content view to be the same XML with the line I generated by clicking a Button.
Thank you.
Code:
public class Dots extends Activity implements View.OnClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dots);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
b[i][j] = (Button) findViewById(refbutton[i][j]);
b[i][j].setOnClickListener(this);
}
}
}
private static class SampleView extends View
{
public SampleView(Context context)
{
super(context);
}
protected void onDraw(Canvas canvas)
{
Paint p = new Paint();
p.setColor(Color.BLACK);
p.setStyle(Paint.Style.STROKE);
canvas.drawLine(5, 5, 25, 5, p);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.dots, menu);
return true;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SampleView d=new SampleView(this);
setContentView(d);
}
}

Related

android invalidate function is not called

when findsellectedtBt() called invalidate in the findSellectedBt() don't work.
so onDraw() is not called.
why these codes don't work correctly ?
public class CustomView extends View {
private Typeface t;
private Paint paint;
private Buttons sellectedBt;
public CustomView(Context context) {
... }
public CustomView(Context context, AttributeSet attrs) {
...}
public CustomView(Context context, AttributeSet attrs, int defStyle) {
...}
#Override
protected void onDraw(Canvas canvas) {
if(isInEditMode()) return ;
canvas.drawColor(Color.YELLOW);
switch(sellectedBt) {
case ID:
t = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL);
paint.setTypeface(t);
canvas.drawText("ID: 0000", 50, 100, paint);
case PHOTO:
break;
case LINE:
break;
default:
break;
}
}
public void findSellectedBt(Buttons buttonId ) {
sellectedBt = buttonId;
invalidate();
}
}
public class MainActivity extends Activity {
private CustomView customView;
private Button btId;
private CheckBox btPhoto;
private ToggleButton btLineOff;
private Button btClaer;
private ToggleButton btBlue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customView = new CustomView(this);
btId = (Button)findViewById(R.id.id);
btPhoto = (CheckBox)findViewById(R.id.photo);
btId.setOnClickListener(new OnClickListener() {
public void onClick(View v){
System.out.println("idOnclick");
customView.findSellectedBt(Buttons.ID);
}
});
btPhoto.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
System.out.println("photoChecked");
if(arg1 == true)
customView.findSellectedBt(Buttons.PHOTO);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
package com.example.hw4_200921275;
public enum Buttons {ID, PHOTO, LINE, CLEAR, BLUE}
Double check you're somewhere calling
findSellectedBt(buttonsObject);
By the way, notice the typo in Sellected.

Call a method from activity that extends View

I'm doing a genre of a bull's eye, but instead of use circles I'm using squares.
But the problem is:
Everything is done, the algorithm to generate the color the others squares is done.
But I implemented a button, and I made it to refresh the bull's eye.
The problem is that I can't make, need help.
This is the MainActivity, it's from here that I will detect the button click.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FrameLayout frame = (FrameLayout) findViewById(R.id.frame);
Draw draw = new Draw(this);
frame.addView(draw);
Button refresh = (Button) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
draw.onDraw(canvas);
frame.addView(draw);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And this is the Draw activity, this is the one that I used to render the image.
public class Draw extends View {
public Draw(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
Paint prop = new Paint();
Random color = new Random();
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
int oriwidth = 0;
int oriheight = 0;
for (int x = 0; x < 20; x++) {
int red = color.nextInt();
int green = color.nextInt();
int blue = color.nextInt();
prop.setARGB(0, red, green, blue);
canvas.drawRect(oriwidth += 10, oriheight += 10, width -= 10,
height -= 10, prop);
}
}
}
Can someone help me? Sorry for the english.
Is there any special reason why you're adding the Draw view programmatically during onCreate?
Try defining the Draw view in the layout xml itself. That should solve any issues with defining the width / height of the view (make sure to define width & height... try hard coded dimensions at first like 100dp by 100dp)
Once you've done that, make sure to capture your "draw" view as a member of the activity:
public class MainActivity extends Activity
{
private Draw mDraw;
Then, in your onCreate:
mDraw = (Draw)findViewById(R.id.myDrawId);
Then, in your button click listener, just call invalidate:
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDraw.invalidate();
}
});
Try to change with this portion of code:
public void onClick(View v) {
MainActivity.this.draw.onDraw(canvas);
MainActivity.this.frame.addView(draw);
}
You shouldn't call onDraw() directly. Try draw.invalidate().

Drag and Drop help - Android

I'm using Android Studio to create a small drag and drop application. I have followed all the rules I know and the code doesn't seem to have any errors, however when I run it on my device it simple crashes. Anyone know where its wrong?
The code is fine until initialise(); is called in public void blue(View v)
so I'm suspecting the error is there
public class MainActivity extends Activity {
private ImageView blueball;
private ImageView blueballdrag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void colourGen(View view){
int i =1;
if (i==i){
blue(view);
}
}
public void brown(View v){
setContentView(R.layout.activity_brown);
}
public void yellow (View v){
setContentView(R.layout.activity_yellow);
}
public void green (View v){
setContentView(R.layout.activity_green);
}
public void blue (View v){
setContentView(R.layout.activity_blue);
initialise();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void initialise() {
final ImageView imageView = (ImageView) blueballdrag.findViewById(R.id.imageView4);
imageView.setOnDragListener(new View.OnDragListener() {
public boolean onDrag(View v, DragEvent dragEvent) {
switch (dragEvent.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
v.setBackgroundColor(Color.RED);
case DragEvent.ACTION_DRAG_ENTERED:
v.setBackgroundColor(Color.BLACK);
case DragEvent.ACTION_DRAG_ENDED:
v.setBackgroundColor(Color.GREEN);
case DragEvent.ACTION_DROP:
v.setBackgroundColor(Color.WHITE);
}
return false;
}
});
blueball = (ImageView) findViewById(R.id.imageView6);
blueball.setOnLongClickListener(new OnLongClickListener(){
#Override
public boolean onLongClick(View v) {
View.DragShadowBuilder myShadow = new MyDragShadowBuilder(blueball);
v.startDrag(null, myShadow, null, 0);
return false;
}
});
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static class MyDragShadowBuilder extends View.DragShadowBuilder {
private static Drawable shadow;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public MyDragShadowBuilder(View v) {
super(v);
shadow = new ColorDrawable(Color.RED);
}
public void onProvideShadowMetrics(Point size, Point touch){
int width, height;
width = getView().getWidth() * 2;
height = getView().getHeight() * 2;
shadow.setBounds(0, 0, width, height);
size.set(width, height);
touch.set(width*2, height*2);
}
public void onDrawShadow(Canvas canvas){
shadow.draw(canvas);
}
}
}
The problem is the line
final ImageView imageView = (ImageView) blueballdrag.findViewById(R.id.imageView4);
This line tells the Object blueballdrag to find a child view called imageView4. I'm guessing that your ImageViews don't have children. You want the findViewById() method of your Activity, not your View.
Changing the line to the following should solve your problem.
final ImageView imageView = (ImageView) findViewById(R.id.imageView4);

Custom view inherited from LinearLayout can not display

layout_main.xml:
<RelativeLayout 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:background="#ffffff"
tools:context=".MainActivity" >
<com.example.testandroid.MainView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
MainView:
public class MainView extends ViewGroup {
public MainView(Context context, AttributeSet as) {
super(context);
addView(new ZoomController(context));
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0, len = getChildCount(); i < len; i++) {
View v = getChildAt(i);
v.layout(0, 0, r - l, b - t);
}
}
}
ZoomController:
public class ZoomController extends LinearLayout {
private Button zoomIn;
public ZoomController(Context context) {
super(context);
zoomIn = new Button(context);
zoomIn.setText("+");
setOrientation(1);
addView(zoomIn);
}
}
When I run the application, I got a blank screen.
Why the zoomIn button was not visible?
This might not be the answer you are looking for, but if you have MainView extend LinearLayout instead of ViewGroup it works fine.
Please try it..
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.buttonLayout);
linearLayout.addView(new ZoomController(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class ZoomController extends LinearLayout {
private Button zoomIn;
public ZoomController(Context context) {
super(context);
zoomIn = new Button(context);
zoomIn.setText("+");
setOrientation(1);
addView(zoomIn);
}
}
}

How can I change the picture that draws on the screen

This might seem like a silly qustion but how do you change the picture that draws on the screen.I have already been able to program a app were it draws a little icon where you touch the screen.So natually after I completed that I want to make it better by adding a option menu and the ability to change what icon you were being drown but when I ran the code the icon picture stayed the same.When I looked at it I found that when you click on any of the menu item it does do it's job and change the image id but when you go back to the main screen and try to create a new image it revertes back to the old image.I have no idea why it doesn't change because when I look at it everything make sense for it to change icon properly.If any one has any idea on what i am doing wrong or any suggestion on how to do this it would be greatly appreciate
Main
public class main extends Activity {
/** Called when the activity is first created. */
MenuItem item2;
int item3=R.drawable.ic_launcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout sv = new FrameLayout(this);
LinearLayout ll = new LinearLayout(this);
Panel test = new Panel(this);
//ImageButton button = new ImageButton(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(test);
//ll.addView(button);
sv.addView(ll);
setContentView(sv);
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
Log.v("test", "item3 before is: "+item3);
item3=R.drawable.box;
Log.v("test", "item3 after is: "+item3);
return super.onOptionsItemSelected(item);
}
}
Panel
public class Panel extends SurfaceView implements SurfaceHolder.Callback {
private Bitmap image;
private ViewThread mThread;
private int x;
private int y;
private ArrayList<Element> mElements = new ArrayList<Element>();
public Panel(Context context) {
super(context );
image = BitmapFactory.decodeResource(getResources(),yantz.imageapp4.R.drawable.test);
getHolder().addCallback(this);
mThread = new ViewThread(this);
}
public void doDraw(Canvas canvas) {
canvas.drawColor(Color.CYAN);
canvas.drawBitmap(image, x, y, null);
synchronized (mElements){
for(Element element : mElements){
element.doDraw(canvas);
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
Log.v("test", "you have touched the sreen: ");
synchronized (mElements){
mElements.add(new Element(getResources(),(int) event.getX(),(int) event.getY()));
}
return super.onTouchEvent(event);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (!mThread.isAlive()) {
mThread = new ViewThread(this);
mThread.setRunning(true);
mThread.start();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mThread.isAlive()) {
mThread.setRunning(false);
}
}
}
Elements
public class Element extends main{
private int mX;
private int mY;
int location ;
private Bitmap mBitmap;
public Element(Resources res, int x, int y) {
Log.v("element", "item3 before location is: "+item3);
location =item3;
mBitmap = BitmapFactory.decodeResource(res, location);
mX = x - mBitmap.getWidth() / 2;
mY = y - mBitmap.getHeight() / 2;
Log.v("element", "item3 before location is: "+item3);
}
public void doDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, mX, mY, null);
}
public void setlocation(int location2){
location=location2;
}
}
ViewThread
public class ViewThread extends Thread {
private Panel mPanel;
private SurfaceHolder mHolder;
private boolean mRun = false;
public ViewThread(Panel panel) {
mPanel = panel;
mHolder = mPanel.getHolder();
}
public void setRunning(boolean run) {
mRun = run;
}
#Override
public void run() {
Canvas canvas = null;
while (mRun) {
canvas = mHolder.lockCanvas();
if (canvas != null) {
mPanel.doDraw(canvas);
mHolder.unlockCanvasAndPost(canvas);
}
}
}
}
you can use
#Override
protected void onResume() {
super.onResume();
id="what ever you want";
//and set it to imagevIew;
}
if i have understood the uestion correctly,this happens because your activity pauses when it is not focused and resumes with default values.

Categories

Resources