I am using RelativeLayout to position views at precise locations on the screen. This works as expected when using a view that say, draws a rectangle. But when using Android views like EditText, they are drawn shorter than specified by about 8 units. Clicking outside of the drawn EditText (but within the parameters specified by RelativeLayout) will, in fact, hit the EditText.
Here is some code to illustrate what I mean:
package com.DrawDemo;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
public class DrawDemo extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
RelativeLayout l = new RelativeLayout(this);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(100,100);
lp.leftMargin = 50;
lp.topMargin = 50;
DemoView demoview = new DemoView(this);
l.addView(demoview, lp);
EditText editText = new EditText(this);
l.addView(editText, lp);
setContentView(l);
}
private class DemoView extends View
{
public DemoView(Context context)
{
super(context);
}
#Override protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.GREEN);
canvas.drawPaint(paint);
}
}
}
If you execute this, you will notice that the EditText is noticeably shorter than the rectangle. I've tried mucking with onMeasure, setMinimumXXX, and just about everything else I can think of. So far, the only thing that works with some level of success is to just add 8 or so pixels to the height (8 seems to work better than trying a percentage of the height).
Next task will be to step into the source but was wondering if somebody has already solved this.
Thanks.
It's just because of the actual EditText background image that's used. Buttons are the same way, for some reason Google decided to draw the 9-patch background images with some extra transparent padding pixels. Really, the only solution, if it's a problem, would be to draw your own 9-patch, or modify the existing Android 9-patch to remove the extra pixels.
Related
Follows is an SSCCE to understand animation timing, extracted from a much more complicated example. What this example when completed should do is create a circle and change its fill color between red and green every second. Right now it just draws a red circle and then nothing else. I've tried placing Runnable, Timer, Thread, and Handler code in various locations but it never seems to do anything. Another problem I've encountered in run() methods is the need for references to Canvas and the current color and the only way I've obtained them is by creating member data for them which, especially in the case of Canvas, seems like a bad idea. For what I'm ultimately doing, rotation and translation of graphic objects, SampleView and the accompanying Canvas seems to be almost certainly necessary so I want to leave SampleView in place. I think that's part of the problem, most examples of animation I've encountered place the timing code in an Activity but that won't work cleanly since the inner View's canvas must be used to update the color (unless I'm missing something).
Inside run methods I used variations on code like this.
if (color == Color.RED)
color = Color.GREEN;
else color = Color.RED;
canvas.drawOval(rectF, p);
hand.postDelayed(run, GET_DATA_INTERVAL);
Those references to color and canvas have been a pain.
package com.example.circles;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private static class SampleView extends View {
public SampleView(Context context) {
super(context);
setFocusable(true);
p = new Paint();
}
Paint p;
int color;
RectF rectF = new RectF(0, 0, 50, 50);
#Override
protected void onDraw(Canvas canvas) {
p.setStyle(Paint.Style.FILL);
color = Color.RED;
p.setColor(color);
canvas.drawOval(rectF, p);
}
}
}
I'm stucked in this for almost a month. I have a perfect chart in my android code using 'afreechart', however, the library does not seem to have support for exporting the chart as an image yet (since it's based on 'jfreechart' and this one does the job).
I tried to get the view of the chart, convert it into canvas and save using the compress functions of the bitmap library, however everytime i try this i get a totally black image as a result. I tried this same method and it works for the other views of my code (simple views, like linearlayout and relativelayout).
After that i tried to create a routine to make a screenshot of the chart activity and close that activity after that. But I couldn't find a way to do that by code, the closest i got was with monkeyrunner.
So i gave up of this idea and tried to look for other libraries, such as 'kichart', 'achartengine', etc, but none of them seem to do the job for, i'm freaking out and i thought that exporting the chart to an image wouldn't be that hard... any ideas?
When i set a background color for the layout, the returned image is a full rectangle with the color of the background, so it's getting the layout, just not the chart.
My Code:
package com.kichart;
import java.io.File;
import java.io.FileOutputStream;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
public class Main extends Activity {
LinearLayout ll;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
float[] values = new float[] { 2.0f,1.5f, 2.5f, 1.0f , 3.0f };
String[] verlabels = new String[] { "great", "ok", "bad" };
String[] horlabels = new String[] { "today", "tomorrow", "next week", "next month" };
GraphView graphView = new GraphView(this, values, "GraphViewDemo",horlabels, verlabels, GraphView.BAR);
ll = new LinearLayout(this);
ll.addView(graphView);
Draw2d d = new Draw2d(this);
setContentView(d);
//setContentView(graphView);
}
public class Draw2d extends View {
public Draw2d(Context context) {
super(context);
setDrawingCacheEnabled(true);
}
#Override
protected void onDraw(Canvas c) {
ll.setBackgroundColor(Color.WHITE);
ll.measure(MeasureSpec.getSize(ll.getWidth()), MeasureSpec.getSize(ll.getHeight()));
ll.layout(400, 400, 400, 400);
ll.draw(c);
try {
getDrawingCache().compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(new File("/mnt/sdcard/graph2.png")));
} catch (Exception e) {
Log.e("Error--------->", e.toString());
}
super.onDraw(c);
}
}
}
You can get a image bitmap from a view by doing:
Bitmap bitmap;
chart.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(chart.getDrawingCache());
chart.setDrawingCacheEnabled(false);
if you can't call getDrawingCache on the chart, try to place it inside a layout like RelativeLayout or something like that. and call it on the layout.
After that you can save it as a image..
If the image is still black, you need to make sure the chart is created before getting the bitmap.
Hope this will help you
I'm new to the Android SDK so I'm trying to figure this out. I have read the documentation and a text book and they haven't been particularly helpful in this matter.
I'm just trying to draw a simple rectangle in a linear layout on the screen. I can't get the shape to show up, however, when I add text to this layout in the same fashion, the text does show up. What am I missing?
package jorge.jorge.jorge;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ShapesActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ShapeDrawable rect = new ShapeDrawable(new RectShape());
rect.getPaint().setColor(Color.GREEN);
ImageView view1 = new ImageView(this);
view1.setImageDrawable(rect);
LinearLayout frame = (LinearLayout)findViewById(R.id.linear1);
frame.addView(view1);
// TextView tx = new TextView(this);
//
// tx.setText("Hello World");
//
// frame.addView(tx);
}
}
The Shape is usually used for making a background to some View. Its width and height is the same of the view that is using it. Then, if this view has no width and height, It'll have no width and height, too.
Basically, I think that your ImageView has no width and height, then it's invisible.
You can see how to set it programatically here:
Set ImageView width and height programmatically?
But, I recomend you to make the layout in XML's way.
I have one activity in my Android App for now which is a RelativeLayout with a background color and onCreate I create a number of random colored circles and addViews on to the relativelayout based on the device screen width and height. Here are the code snippets.
MyActivity.java
package com.myapp.android;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.Display;
import android.widget.RelativeLayout;
public class MyActivity extends Activity {
/** Called when the activity is first created. */
Random randomGenerator = new Random();
String[] colors = { "#84B62C", "#6A28F2","#F3FA0A", "#DF1FE4", "#0000A0", "#28C9DB", "#E05323"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RelativeLayout main = (RelativeLayout) findViewById(R.id.main_myapp);
// Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
int number_side = width / 100;
int number_down = height / 100;
for(int i = 0; i < (number_side * number_down) * 3; i++) {
main.addView(new Ball(this,randomGenerator.nextInt(width), randomGenerator.nextInt(height), 40 * (randomGenerator.nextInt(3)), colors[randomGenerator.nextInt(colors.length)], "BALL" + Integer.toString(i)));
}
}
}
This works great draws all the colored circles in random throughout the screen as I want it. Looks good. Here is the code for the Ball.java where the circles are drawn.
Ball.java
package com.myapp.android;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
public class Ball extends View {
private final float x;
private final float y;
private final int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public Ball(Context context, float x, float y, int r, String color, String tag) {
super(context);
mPaint.setColor(Color.parseColor(color));
this.x = x;
this.y = y;
this.r = r;
this.setTag(tag);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
}
What I am trying to do is let the user touch any one of the colored circle and drag it on the screen wherever they want to but I cannot get them to move. I have not posted any trial code here.
What would be the best way to detect the user touch (this can be onTouch or onLongClick) on any of the circles drawn on screen (one circle at a time especially the one that is touched by the user) and thereafter make the circle (which is essentially a view added to the main Relative Layout View group at run time) to follow the users touch drag action (ACTION_MOVE - my guess) until they release the drag (ACTION_UP - my guess).
I have read some tutorials on this topic but none has been really helpful or applicable to my use case. Also I wanted to ask you knowledgeable guys should I use the 2D Graphics Canvas or OpenGL API in my case so that the drag operation on the circles are very smooth and instantaneous. Feel free to run my simple code, it works fine until the balls are drawn on the screen.
In your implementation, you consider Ball as a View and there are many balls thus there are many Views.
If I were you, I'll consider the whole screen is ONE View and the balls are only sprites inside that View.
Say, I'll extend the View class or SurfaceView class and have a Collection as attribute to store all coordinates and sizes of balls. Inside onDraw(), it should loop through the collection and draw the balls on correct location with correct size.
Here is my unanswered question:
Add new item count to icon on button - Android
Basically I want to display "new" counts on top. I see it as overlaying some view over existing button. How this can be done?
Easiest thing to do is:
Use a RelativeLayout with layout_height and layout_width set to WRAP_CONTENT.
Put one Button into the RelativeLayout with layout_height and layout_width set to WRAP_CONTENT.
Add an ImageView into the RelativeLayout aligned to PARENT_TOP and PARENT_RIGHT and set the visibility to GONE.
Then you can simply set the ImageView's drawable to the appropriate count image and set the visibility to VISIBLE.
Ok here is what i'd do:
Create a custom control that extends button. I'm not going to do the pretty graphics for you but this will give you the basic idea:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.Button;
public class CounterButton extends Button{
protected int count=0;
protected final Paint myTextPaint = new Paint();
protected final Paint myCirclePaint = new Paint();
public CounterButton(Context context, AttributeSet attrs) {
super(context, attrs);
this.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.ic_dialog_email));
this.myCirclePaint.setARGB(150, 255, 0, 0);
this.myTextPaint.setARGB(150, 255, 255, 255);
}
#Override
protected void onDraw(Canvas canvas) {
if(count!=0){
canvas.drawCircle((float) (this.getWidth()*.75), (float) (this.getHeight()*.4), this.getHeight()/5, myCirclePaint);
canvas.drawText(Integer.toString(count), (float) (this.getWidth()*.75), (float) (this.getHeight()*.4), this.myTextPaint);
}
}
}
Clean up the sizing of your text you draw, the circle positioning (and add a border etc) and you have a custom control. You could further extend it so you could set the background in xml or dynamically and you have a reusable control with a number counter in a circle.
then in your code you could do:
CounterButton cb=(CounterButton) findViewById(R.id.whateverYouGaveItInXML);
cb.count=SomeNewNumber;
cb.invalidate;
the invalidate will redraw the image with the new value in the circle.
I used a button in the event you want to have it clickable easily and all that - but you could just as easily extend view if you are just doing a view.