I am using below custom class for make text outline in my quotes application. Its working fine till device with android 9. In android 10 device, its not giving me any error as well not working.
My custom class for draw outline is like below
public class OutlineTextView extends androidx.appcompat.widget.AppCompatTextView {
private Field colorField;
private int textColor;
private int outlineColor;
public OutlineTextView(Context context) {
this(context, null);
}
public OutlineTextView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.textViewStyle);
}
public OutlineTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
try {
colorField = TextView.class.getDeclaredField("mCurTextColor");
colorField.setAccessible(true);
textColor = getTextColors().getDefaultColor();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OutlineTextView);
outlineColor = a.getColor(R.styleable.OutlineTextView_outlineColor, Color.TRANSPARENT);
setOutlineStrokeWidth(a.getDimensionPixelSize(R.styleable.OutlineTextView_outlineWidth, 0));
a.recycle();
}
catch (NoSuchFieldException e) {
e.printStackTrace();
colorField = null;
}
}
#Override
public void setTextColor(int color) {
textColor = color;
super.setTextColor(color);
}
public void setOutlineColor(int color) {
invalidate();
outlineColor = color;
}
public void setOutlineWidth(float width) {
invalidate();
setOutlineStrokeWidth(width);
}
private void setOutlineStrokeWidth(float width) {
invalidate();
getPaint().setStrokeWidth(2 * width + 1);
}
#Override
protected void onDraw(Canvas canvas) {
if (colorField != null) {
// Outline
setColorField(outlineColor);
getPaint().setStyle(Paint.Style.STROKE);
super.onDraw(canvas);
// Reset for text
setColorField(textColor);
getPaint().setStyle(Paint.Style.FILL);
}
super.onDraw(canvas);
}
private void setColorField(int color) {
// We did the null check in onDraw()
try {
colorField.setInt(this, color);
}
catch (IllegalAccessException | IllegalArgumentException e) {
// Optionally catch Exception and remove print after testing
e.printStackTrace();
}
}
}
I am calling it from my RecyclerView like this
CardMainActivity.text_quotes.setOutlineColor(Color.parseColor(CardConstant.getcolorcodearray().get(getAdapterPosition())));
My gradle build information is like below
compileSdkVersion 29
buildToolsVersion "29.0.2"
Let me know if someone can help me. Thanks!
Related
I am trying to clip a path in my custom view but it appears black in color. Through searching and finding the reason for same. Found that I need to set " setLayerType(LAYER_TYPE_SOFTWARE,null)". After this it appears perfect but crashes in some deivices.
Crash Log(One of these based on devices):
java.lang.NegativeArraySizeException
Bitmap exceeds 32bit
public class CardLayout extends LinearLayout {
private View mRoot;
private ImageView mCategoryImageView;
private LinearLayout mCategoryBottomView;
private RectF mRect;
private Paint mPaint;
private View mDivider;
private Path mPath;
private int mPadding = 30;
public CardLayout(Context context) {
super(context);
}
public CardLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CardLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
mRoot = LayoutInflater.from(getContext()).inflate(R.layout.card_content, null);
addView(mRoot);
initUI();
}
private void initUI() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
mPath = new Path();
mCategoryHeadlineTextView = (TextView) mRoot.findViewById(R.id.categoryHeadline);
mCategoryImageView = (ImageView) mRoot.findViewById(R.id.categoryImageView);
mCategoryBottomView = (LinearLayout) mRoot.findViewById(R.id.ctg_btm_view);
mDivider = mRoot.findViewById(R.id.divider);
setLayerType(LAYER_TYPE_SOFTWARE,null);
}
public void setCategoryImage(String categoryUrl) {
if (mCategoryImageView != null) {
Glide.with(mContext)
.load(categoryUrl)
.placeholder(R.drawable.two)
.into(mCategoryImageView);
}
}
public void setBottomView(String[] optionText, int[] optionResource, int tag) {
if (mCategoryBottomView != null) {
CategoryBottomOptions options = new CategoryBottomOptions(mContext, optionText, optionResource, tag, mCategoryBottomView);
}
}
#Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
mRect = new RectF(mDivider.getX() - mPadding, mDivider.getY() - mPadding, mDivider.getX() + mPadding, mDivider.getY() + mPadding);
mPath.addArc(mRect, 270, 180);
canvas.clipPath(mPath);
canvas.drawPath(mPath, mPaint);
mRect = new RectF(mDivider.getWidth() - mPadding, mDivider.getY() - mPadding, mDivider.getWidth() + mPadding, mDivider.getY() + mPadding);
mPath = new Path();
mPath.addArc(mRect, 90, 180);
canvas.clipPath(mPath);
canvas.drawPath(mPath, mPaint);
}
}
You Should do something like this to create a window withing a view.
public class ClippedImageView extends ImageView {
private Paint mPaint;
private Path mPath;
public ClippedImageView(Context context) {
this(context, null);
init();
}
public v(Context context, AttributeSet attrs) {
this(context, attrs, 0);
init();
}
public ClippedImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
mPath = new Path();
RectF rect = new RectF(0, 0, 100, 100);
mPath.addArc(rect, 270, 180);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.clipPath(mPath, Region.Op.DIFFERENCE);
super.onDraw(canvas);
}
}
Hi I drew a bitmap on the canvas and I wanted to do something when the user touches it.
Bitmap backbutton = BitmapFactory.decodeResource(getResources(),
R.drawable.backbutton);
Paint paint = new Paint();
canvas.drawBitmap(backbutton, canvasWidth - 100, 0, paint);
I have tried the following to solve the problem but it isnt working. How do I check for inbounds properly?
public void onTouch(View view, MotionEvent event) {
if(backbutton.contains((int) (event.getX()), (int)(event.getY()), (int)(event.getX()+100),(int) (event.getY()+30))) {
Toast.makeText(view.getContext(), "this works", Toast.LENGTH_LONG).show();
}
}
But I seem to be doing something wrong with the contains(). Can someone help me out here please?
First get the rect of the bitmap on the canvas. then in the onTouchEvent, check the touched x, y is contained in the rect before.
Added Example:
public class MyView extends View {
Rect bitmapRect;
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas); //To change body of overridden methods use File | Settings | File Templates.
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
Rect source = new Rect(0,0,bitmap.getWidth(), bitmap.getHeight());
bitmapRect = new Rect(0,0, bitmap.getWidth(), bitmap.getHeight());
canvas.drawBitmap(bitmap, source, bitmapRect, new Paint());
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
if(null != bitmapRect && bitmapRect.contains(x,y)){
Toast.makeText(view.getContext(), "this works", Toast.LENGTH_LONG).show();
}
return super.onTouchEvent(event); //To change body of overridden methods use File | Settings | File Templates.
}
}
i'm going to use beyondar framework in my app and i have a problem with the cameraview. Beyondar uses cameraview in landscape mode but i want to use this view only in portrait mode at the half of the screen, as image shows.
BeyondAR CameraView.java
public class CameraView extends SurfaceView implements SurfaceHolder.Callback,
Camera.PictureCallback {
/**
*
* #author Joan Puig Sanz (joanpuigsanz#gmail.com)
*
*/
public static interface IPictureCallback {
/**
* This method is called when the snapshot of the camera is ready. If
* there is an error, the image will be null
*
* #param picture
*/
void onPictureTaken(Bitmap picture);
}
private SurfaceHolder mHolder;
private Camera mCamera;
private IPictureCallback mCameraCallback;
private BitmapFactory.Options mOptions;
private Size mPreviewSize;
private List<Size> mSupportedPreviewSizes;
private List<String> mSupportedFlashModes;
public CameraView(Context context) {
super(context);
init(context);
}
public CameraView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public CameraView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
mHolder = getHolder();
mHolder.addCallback(this);
try {
mCamera = Camera.open();
//mCamera.setDisplayOrientation(90);
Method rotateMethod;
rotateMethod = android.hardware.Camera.class.getMethod("setDisplayOrientation", int.class);
rotateMethod.invoke(mCamera, 90);
//Camera.Parameters params = mCamera.getParameters();
//params.setPreviewSize(427, 1240);
//mCamera.setParameters(params);
setCamera(mCamera);
} catch (Exception e) {
Log.e(Constants.TAG, "ERROR: Unable to open the camera", e);
}
if (android.os.Build.VERSION.SDK_INT <= 10) {// Android 2.3.x or lower
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
}
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
mSupportedFlashModes = mCamera.getParameters().getSupportedFlashModes();
// Set the camera to Auto Flash mode.
if (mSupportedFlashModes != null
&& mSupportedFlashModes.contains(Camera.Parameters.FLASH_MODE_AUTO)) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
//parameters.setPreviewSize(300, 200);
mCamera.setParameters(parameters);
}
}
}
public void setSupportedPreviewSizes(List<Size> supportedPreviewSizes) {
mSupportedPreviewSizes = supportedPreviewSizes;
}
public Size getPreviewSize() {
return mPreviewSize;
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
try {
if (mCamera == null) {
init(getContext());
if (mCamera == null) {
return;
}
}
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
if (mCamera != null) {
mCamera.release();
}
mCamera = null;
Log.e(Constants.TAG, "CameraView -- ERROR en SurfaceCreated", exception);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when the activity is paused.
if (mCamera == null) {
return;
}
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private Size getOptimalPreviewSize(List<Size> sizes, int width, int height) {
Size result = null;
for (Camera.Size size : sizes) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
}
return result;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (mCamera == null || getPreviewSize() == null) {
return;
}
Camera.Parameters parameters = mCamera.getParameters();
Size previewSize = getPreviewSize();
parameters.setPreviewSize(previewSize.width, previewSize.height);
mCamera.setParameters(parameters);
previewCamera();
}
#Override
public void onPictureTaken(byte[] imageData, Camera camera) {
if (imageData != null && mCameraCallback != null) {
mCameraCallback.onPictureTaken(StoreByteImage(imageData));
}
previewCamera();
}
public void previewCamera() {
if (mCamera == null){
return;
}
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d(Constants.TAG, "Cannot start preview.", e);
}
}
private Bitmap StoreByteImage(byte[] imageData) {
Bitmap myImage = DebugBitmap.decodeByteArray(imageData, 0, imageData.length, mOptions);
imageData = null;
System.gc();
return myImage;
}
public void tackePicture(IPictureCallback cameraCallback) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
tackePicture(cameraCallback, options);
}
public void tackePicture(IPictureCallback cameraCallback, BitmapFactory.Options options) {
if (mCamera == null) {
return;
}
mCameraCallback = cameraCallback;
mCamera.takePicture(null, this, this);
mOptions = options;
}
}
Check out the last version of the library, this issue is fixed and the use of the framework is way better
https://github.com/BeyondAR/beyondar
Using onDraw, I want to make a custom text view that changes color depending on its text value. For example, if the text value is "hello" I want it to be red and if it says "bye" I want it to be green. Any helps greatly appreciated.
I'm not necessarily sure why you want to do this in onDraw(). Unless you have a really good reason to set up a custom TextView/EditText, that's not necessary.
To simplify your situation, you can implement a TextWatcher to do this, and in onTextChanged(), you can set the color by comparing the string values using .equals().
Here is an example of your theoretical situation:
final EditText yourEditText = /* findViewById maybe? */;
yourEditText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.equalsIgnoreCase("hello"))
yourEditText.setTextColor(Color.RED);
else if (s.equalsIgnoreCase("bye"))
yourEditText.setTextColor(Color.GREEN);
else // if it says neither "hello" nor "bye"
yourEditText.setTextColor(Color.BLACK);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Nothing needs to happen here
}
public void afterTextChanged(Editable s) {
// Nothing needs to happen here
}
});
If you feel its necessary to maintain this in onDraw(), simply extract the code from onTextChanged() and change yourEditText to this, or place it in the constructor instead:
public class YourTextView extends TextView { // Or extends EditText, doesn't matter
public YourTextView(Context context) {
this(context, null, 0);
}
public YourTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public YourTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
addTextChangedListener(new TextWatcher() {
// Copy the TextWatcher code from the example above, replacing "yourEditText" with "YourTextView.this"
});
}
// ... Rest of your class
}
I figured out how to do it in a more creative way using onDraw.
public class MagnitudeTextView extends TextView {
public MagnitudeTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MagnitudeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MagnitudeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
/*
* (non-Javadoc)
*
* #see android.widget.TextView#onDraw(android.graphics.Canvas)
*/
#Override
protected void onDraw(Canvas canvas) {
int height = getMeasuredHeight();
int width = getMeasuredWidth();
int px = width / 2;
int py = height / 2;
Paint Red = new Paint(Paint.ANTI_ALIAS_FLAG);
Red.setColor(Color.RED);
Paint White = new Paint(Paint.ANTI_ALIAS_FLAG);
White.setColor(Color.DKGRAY);
Paint Yellow = new Paint(Paint.ANTI_ALIAS_FLAG);
Yellow.setARGB(210, 105, 30, 0);
Paint Blue = new Paint(Paint.ANTI_ALIAS_FLAG);
Blue.setColor(Color.BLUE);
float textWidth = Red.measureText(String.valueOf(getText()));
String g = String.valueOf(getText());
if (g.startsWith("3") || g.startsWith("4")) {
canvas.drawText(String.valueOf(getText()), px - textWidth / 2, py,
White);
}
if (g.startsWith("6") || g.startsWith("5") || g.startsWith("7")
|| g.startsWith("8")) {
canvas.drawText(String.valueOf(getText()), px - textWidth / 2, py,
Yellow);
}
if (g.startsWith("9") || g.startsWith("10")) {
canvas.drawText(String.valueOf(getText()), px - textWidth / 2, py,
Red);
}
// super.onDraw(canvas);
}
}
You can overwrite setText() and set the color using setTextColor().
You can do it inside onDraw as well, but it's not worth the weigth, as it may pass many times inside onDraw.
You can implement TextWatcher and use onTextChanged()
More about it here in the Android Docs
Use this to get the text:
TextView text = (TextView)findViewById(R.id.textid);
String value = text.getText().toString();
Then check what the text is and change the color :
if (value.equals("hello")) {
text.setBackgroundColor(yourcolor);
}
I am using Translate Animation for moving an ImageView. I am using this code:
TranslateAnimation set1 = new TranslateAnimation(-4, 10, -110, 0);
set1.setDuration(3000);
TranslateAnimation set2 = new TranslateAnimation(10, -3, 0, 115);
set2.setDuration(3000);
set2.setStartOffset(2200);
TranslateAnimation set3 = new TranslateAnimation(-3, -20, 0, -100);
set3.setDuration(3000);
set3.setStartOffset(4500);
TranslateAnimation set4 = new TranslateAnimation(0, 13, 0, -120);
set4.setDuration(3000);
set4.setStartOffset(6500);
animSet.addAnimation(set1);
animSet.addAnimation(set2);
animSet.addAnimation(set3);
animSet.addAnimation(set4);
animSet.setFillAfter(true);
After creating a set of animations, I apply them on the ImageView like this:
image = (ImageView)findViewById(R.id.img);
image.startAnimation(animSet);
Everything is working fine, but I cannot pause the animation and resume on button click.
How can I do that?
I tried everything, but didn't succeed. Any idea how to do this?
Please help!
After searching for a time i found this link and check is this working for Translate Animation or not and after some modification this is working for your animation too.!
See modified code below:
public class TranslateAnim extends TranslateAnimation{
public TranslateAnim(float fromXDelta, float toXDelta, float fromYDelta,
float toYDelta) {
super(fromXDelta, toXDelta, fromYDelta, toYDelta);
// TODO Auto-generated constructor stub
}
private long mElapsedAtPause=0;
private boolean mPaused=false;
#Override
public boolean getTransformation(long currentTime, Transformation outTransformation) {
if(mPaused && mElapsedAtPause==0) {
mElapsedAtPause=currentTime-getStartTime();
}
if(mPaused)
setStartTime(currentTime-mElapsedAtPause);
return super.getTransformation(currentTime, outTransformation);
}
public void pause() {
mElapsedAtPause=0;
mPaused=true;
}
public void resume() {
mPaused=false;
}
}
I'll only change class name, extends class name and constructor of this class.
you can use it like:
TranslateAnim set1, set2, set3, set4; // objects of TranslateAnim Class
set1 = new TranslateAnim(-4, 10, -110, 0); // initialize all objects like this way
animSet.addAnimation(set1); // add all animation objests in your animation set as you do before
animSet.setFillAfter(true);
and after start your animation you have only call pause and resume methods.
Thanks to Johan for share his code with us.
Hope this solve your problem. :)
You can also do like this: а можно еще так:
public class MyTranslateAnimation extends TranslateAnimation {
private long mTimePause, mTimeTotal;
private boolean mPause;
public MyTranslateAnimation(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean getTransformation(long currentTime, Transformation outTransformation) {
updateTime(currentTime);
return super.getTransformation(mTimeTotal - mTimePause, outTransformation);
}
private void updateTime(long currentTime) {
long dt = currentTime - mTimeTotal;
mTimeTotal += dt;
if (mPause) {
mTimePause += dt;
}
}
public void pause() {
mPause = true;
}
public void resume() {
mPause = false;
}
}
To create an animation from an XML, you can create your own AnimationUtils subclass, like this: для создания анимации из XML можно сделать свой AnimationUtils:
public class MyAnimationUtils {
public static Animation loadAnimation(Context context, int id) throws Resources.NotFoundException {
XmlResourceParser parser = null;
try {
parser = context.getResources().getAnimation(id);
return createAnimationFromXml(context, parser);
} catch (XmlPullParserException ex) {
Resources.NotFoundException rnf = new Resources.NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id));
rnf.initCause(ex);
throw rnf;
} catch (IOException ex) {
Resources.NotFoundException rnf = new Resources.NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id));
rnf.initCause(ex);
throw rnf;
} finally {
if (parser != null) parser.close();
}
}
private static Animation createAnimationFromXml(Context c, XmlPullParser parser) throws XmlPullParserException, IOException {
return createAnimationFromXml(c, parser, null, Xml.asAttributeSet(parser));
}
private static Animation createAnimationFromXml(Context c, XmlPullParser parser, AnimationSet parent, AttributeSet attrs) throws XmlPullParserException, IOException {
Animation anim = null;
// Make sure we are on a start tag.
int type;
int depth = parser.getDepth();
while (((type=parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth)
&& type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("set")) {
anim = new AnimationSet(c, attrs);
createAnimationFromXml(c, parser, (AnimationSet)anim, attrs);
} else if (name.equals("alpha")) {
anim = new AlphaAnimation(c, attrs);
} else if (name.equals("scale")) {
anim = new ScaleAnimation(c, attrs);
} else if (name.equals("rotate")) {
anim = new RotateAnimation(c, attrs);
} else if (name.equals("translate")) {
//anim = new TranslateAnimation(c, attrs);
anim = new MyTranslateAnimation(c, attrs); // отредактировали только эту строчку, остальное взяли как было
} else {
throw new RuntimeException("Unknown animation name: " + parser.getName());
}
if (parent != null) {
parent.addAnimation(anim);
}
}
return anim;
}
}
And then you build the animation like this: и вот так создаем анимацию:
MyTranslateAnimation cloud1 = (MyTranslateAnimation) MyAnimationUtils.loadAnimation(this, R.anim.main_cloud1);
Hope this helps. Пользуйтесь на здоровье!