Android - Canvas Doesn't Show - java

I have researched this on Stack Overflow, but I didn't find the fix to my problem. I have a view that contains the code for a vertical, yellow line on the screen. I have an activity that creates the dialog whose content view is an instance of the view. The dialog pops up, but the yellow line doesn't show. What am I missing? Here is my code:
View :
public guidelines(Context context) {
super(context);
int x = this.getWidth()/2 - 3;
int y = this.getHeight();
shape = new ShapeDrawable(new RectShape());
shape.getPaint().setColor(Color.YELLOW);
shape.setBounds(x, 0, x+6, y);
}
#Override
protected void onDraw(Canvas canvas) {
shape.draw(canvas);
}
Layout for the View :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/---
android:layout_width="match_parent" android:layout_height="match_parent">
<!-- <--- android:background="#ccc"
android:layout_width="300dp" android:layout_height="300dp" android:paddingLeft="20dp"
android:paddingBottom="40dp" app:exampleDimension="24sp" app:exampleColor="#33b5e5"
app:exampleString="Hello, guidelines" /> -->
< ---
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/frame"/>
</FrameLayout>
Dialog Calling Code :
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
guidelines g = new guidelines(this);
dialog.setContentView(g);
dialog.show();
Thanks.

It was better to just use the drawRect function of the canvas. I did that and it worked.

Related

How to make vertical seekbar with progress text as thumb

I want to create a vertical seekbar with progress displaying near to thumb.
I created vertical seekbar by overriding Seekbar class and rotate the canvas. But I don't know how to make the text near to thumb.
#Override
protected final void onDraw(#NonNull final Canvas c) {
if (null == mPaint) {
mPaint = new Paint();
mPaint.setColor(Color.BLACK);
mPaint.setTextSize(50);
}
c.rotate(ROTATION_ANGLE);
c.translate(-getHeight(), 0);
super.onDraw(c);
Rect rect = getThumb().getBounds();
c.drawText(getProgress()+"%", rect.exactCenterX(), rect.exactCenterY(), mPaint);
}
So the problem is If I drawText like this the text also rotated.
So how to fix this?
Meanwhile, I tried some custom View implementation and I am a noob on that.
Update to Khemraj's answer
Actually changing the thumb is the simple trick as said by Khemraj. But the problem is when rotating the canvas all its contents will rotate(simple logic). When updating the thumb also will reflect this problem. So the simple thing is to make a rotated CustomTextView.
Method to make thumb
public Drawable getThumb(int progress) {
int width = getWidth();
((TextView) mThumbView.findViewById(R.id.tvProgress)).setText(String.format(Locale.getDefault(), "%d%%", progress));
mThumbView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
Bitmap bitmap = Bitmap.createBitmap(mThumbView.getMeasuredWidth(), mThumbView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
mThumbView.layout(0, 0, mThumbView.getMeasuredWidth(), mThumbView.getMeasuredHeight());
mThumbView.draw(canvas);
return new BitmapDrawable(getResources(), bitmap);
}
The layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
<ImageView
android:layout_marginTop="30dp"
android:id="#+id/imageView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/seek_thumb_gray"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.samsung.lighting.presentation.ui.custom_views.RotatedTextView
android:id="#+id/tvProgress"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:gravity="center"
android:text="20%"
android:textColor="#000000"
android:textSize="12sp"
app:angle="90"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView6" />
</android.support.constraint.ConstraintLayout>
The RotatedTextView
public class RotatedTextView extends AppCompatTextView {
private int mRotationAngle = 90;
#Override
protected void onDraw(Canvas canvas) {
if (mRotationAngle == 90) {
canvas.rotate(mRotationAngle);
canvas.translate(0, -getWidth());
} else if (mRotationAngle == -90) {
canvas.rotate(mRotationAngle);
canvas.translate(-getHeight(), 0);
}
super.onDraw(canvas);
}
}
So first we will rotate the Text to 90 or -90 degrees and set as thumb to VerticalSeekBar and in vertical seekbar rotate the canvas to 90 or -90 degrees. So finally we will get the actual result
Here I posted the working example.
Thanks, Khemraj

android: display an image in the middle of the screen programatically

I've an image (image1.png)
When I click on some button, I want this image to be displayed in the middle of the screen for a second and disappear. How can I do it?
I guess that it brings me the center coordinates of the screen.
public void onClick(View button) {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics( dm );
int screenMiddlePointWidth = dm.widthPixels / 2;
int screenMiddlePointHeight = dm.heightPixels / 2;
}
p.s. I don't want the image to push other views on the screen so I can't set it as invisible\gone
Hi use this code in xml to place your image in center
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.myapplication.MainActivity"
tools:showIn="#layout/activity_main">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/image1"
android:layout_centerInParent="true"/>
</RelativeLayout>
and then in java file use the following code
ImageView img;
img=(ImageView)findViewById(R.id.imgview);
CountDownTimer timer = new CountDownTimer(1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
img.setVisibility(View.GONE);
}
};
timer.start();
you can use the timer code in onCreate method or anywhere you want.
If you want to center your image programatically use the following code.
image.setBackgroundResource(R.drawable.image1);
LayoutParams params = (LayoutParams) image.getLayoutParams();
params.gravity = Gravity.CENTER;
img.setLayoutParams(params);

Fail to position android popupwindow relative to its size (Android API8)

I want to position a popup window as a tooltip above another view + offset according to the popup size.
I have tried few ways unsuccessfully:
1) Try 1 : using showAtPosition() twice.
// The method that displays the popup.
public void showPopup(View viewToPointAt) {
this.mViewToPointAt = viewToPointAt;
mPopUpView = mActivity.getLayoutInflater().inflate(R.layout.tooltip_share, null);
mPopup =
new PopupWindow(mPopUpView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
mPopup.showAtLocation(mPopUpView, Gravity.NO_GRAVITY, 0, 0); // Displaying popup
ViewTreeObserver vto = mPopUpView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mPopUpView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
mArrowPoint = new Point();
mPopupRect = locatePopup(mPopUpView);
mArrowPoint.x = mPopupRect.right - DisplayUtils.dpiToPixels(10);
mArrowPoint.y = mPopupRect.bottom;
mRectToPointAt = locateView(mViewToPointAt);
mPopUpView.bringToFront();
mPopup.setFocusable(false);
mPopup.setOutsideTouchable(true);
mPopup.showAtLocation(mPopUpView, Gravity.NO_GRAVITY,
mRectToPointAt.right - mArrowPoint.x,
mRectTo
PointAt.top - mArrowPoint.y); // Displaying popup
}
});
}
result: the popup is still at (0,0)
2) Try 2 : using update(..)
// The method that displays the popup.
public void showPopup(View viewToPointAt) {
this.mViewToPointAt = viewToPointAt;
mPopUpView = mActivity.getLayoutInflater().inflate(R.layout.tooltip_share, null);
mPopup =
new PopupWindow(mPopUpView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
mPopup.showAtLocation(mPopUpView, Gravity.NO_GRAVITY, 0, 0); // Displaying popup
ViewTreeObserver vto = mPopUpView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mPopUpView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
mArrowPoint = new Point();
mPopupRect = locatePopup(mPopUpView);
mArrowPoint.x = mPopupRect.right - DisplayUtils.dpiToPixels(10);
mArrowPoint.y = mPopupRect.bottom;
mRectToPointAt = locateView(mViewToPointAt);
mPopUpView.bringToFront();
mPopup.setFocusable(false);
mPopup.setOutsideTouchable(true);
mPopup.update(mViewToPointAt, 0, 0, -1, -1);
}
});
}
result: the popup is aligned to the screen bottom. No matter how big the offset I give it
My tooltip_share.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tooltip_layout"
android:layout_width="290dp"
android:layout_height="wrap_content"
android:background="#drawable/tip_tool_top_right"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingBottom="15dp"
android:paddingLeft="0dp"
android:paddingRight="25dp"
android:paddingTop="5dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:src="#drawable/tip_tool_icon_plane" />
</LinearLayout>
</LinearLayout>
What do i do wrong?
I suggest you to use below library :-
https://play.google.com/store/apps/details?id=com.haarman.supertooltips
https://github.com/nhaarman/supertooltips
You have to create popup.xml as per your popup design ...after then you have to call popup whenever you want.
write code on Create :
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
popupView = layoutInflater.inflate(R.layout.popup, null);
popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
on Button Click :
popupWindow.showAsDropDown(btn_share, 50, -30);

popup window over canvas Android

I am building an application which display a map (the map is the canvas background) and localise users by adding circle on the canvas(using draw circle). I would like to add a button over the canvas(for now a draw a button on the map and check with ontouch() if the user clicked on it) and when the button is touched I would like to have a window popup. It worked but the popup is behind the canvas(I could see a small piece of it(I removed it)).Is there a way to have my canvas BEHIND the button and the popup window? I saw people talking about putting the canvas in relative layout but I have no idea how to do that.
Here is the xml of my activity, really simple:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/umap2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Button" />
</RelativeLayout>
And here is my activity java code(I removed a couple of things that doesnt have nothing to do with my problem)
package com.example.client;
import java.util.LinkedList;
//....
import java.util.Timer;
public class Campus extends Activity{
final Handler myHandler = new Handler();
MapView mapv;
final Activity self = this;
Float ratioX;
Float ratioY;
int width;
int height;
static boolean out=false;
Intent i;
//creating a linked list for each hall
static LinkedList<compMac> DMS = new LinkedList<compMac>();
static LinkedList<compMac> MCD = new LinkedList<compMac>();
//...
static LinkedList<compMac> SCI = new LinkedList<compMac>();
static LinkedList<compMac> STE = new LinkedList<compMac>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.campus);
setSize();
this.mapv = new MapView(this);//!! my view
setContentView(mapv);
i= new Intent(this, myService.class);
this.startService(i);
}
//*******************************View class!*******************************
public class MapView extends View {
/*
* Extract the connected users and location from the array. separate the
* array into an array for each building
* */
private Paint redPaint;
private float radius;
Canvas canvas;
public MapView(Context context) {
super(context) ;
redPaint = new Paint();
redPaint.setAntiAlias(true);
redPaint.setColor(Color.RED);
redPaint.setTextSize(10);
}
#Override
//drawing a point on every hall on the map where users are connected
public void onDraw (Canvas canvas) {
// draw your circle on the canvas
if(!out)
{
AlertDialog.Builder outOfCampus = new AlertDialog.Builder(self);
outOfCampus.setTitle("Sorry");
outOfCampus.setMessage("You are out of Campus");//(toDisplay);
outOfCampus.setCancelable(false);
outOfCampus.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
startActivity(new Intent("com.example.client.Sin"));
}});
AlertDialog alertdialog = outOfCampus.create();
outOfCampus.show();
}
this.canvas=canvas;
setBackgroundResource(R.drawable.umap2);
}
public void drawPoints(LinkedList<compMac> building)
{
if(!building.isEmpty())
{
while(!building.isEmpty())
{
compMac current = building.pop();
Float x= ratioX*(Float.parseFloat(current.getCoorX()));
Float y= ratioY*(Float.parseFloat(current.getCoorY()));
// Log.w("ratioX ",(((Double)(width/768)).toString()));
// Log.w("ratioY ",(float)(y.toString()));
canvas.drawCircle (x,y, 10, redPaint);
}
}
}
public boolean onTouchEvent (MotionEvent event) {
//...//
return true;
}
}
}
Someone have an idea how i can do that? Thanks
Calling setContentView two times would not work. Instead you should put your canvas view and the button in a single layout itself but with proper ordering. The last widget in the relative layout gets more priority, so if you want the button to come on top of the canvas your layout should be something like this.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/umap2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.client.MapView
android:id="#+id/mapView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Button" />
</RelativeLayout>
And to access your MapView in java class
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.campus);
setSize();
this.mapv = findViewById(R.id.mapView); //!! my view
i= new Intent(this, myService.class);
this.startService(i);
}
And obviously alert dialog will be on top of the canvas. Hope it helps!
Edit: I think inflate error is due to incorrect class path. Since MapView is inner class of Campus, path should be like this
<com.example.client.Campus.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Also add this constructor to your MapView class
public MapView(Context context, AttributeSet attributeSet) {
super(context, attributeSet) ;
redPaint = new Paint();
redPaint.setAntiAlias(true);
redPaint.setColor(Color.RED);
redPaint.setTextSize(10);
}
<FrameLayout 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" >
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/umap2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/btn_close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="#drawable/back_transparent_pressed" >
<Button
android:id="#+id/button1"
android:layout_centerInParent="true"
/>
</RelativeLayout>

Custom dialog box width and height

I am trying to make a custom dialog box
LayoutInflater li = LayoutInflater.from(this);
View view = li.inflate(R.layout.rate_layout, null);
RelativeLayout rate = (RelativeLayout) view.findViewById(R.id.rateClick);
RelativeLayout close = (RelativeLayout) view.findViewById(R.id.closeBtn);
close.setClickable(true);
rate.setClickable(true);
final AlertDialog.Builder dd = new AlertDialog.Builder(this);
dd.setView(view);
dd.setCancelable(false);
final AlertDialog d = dd.create();
d.show();
The background image has 4 types of resolutions so I can do wrap content only.
Here is my xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<RelativeLayout
android:id="#+id/rateClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#drawable/rate_now_button" />
<RelativeLayout
android:id="#+id/imageView1"
android:layout_width="219dp"
android:layout_height="234dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#drawable/pop_up" >
<RelativeLayout
android:id="#+id/closeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/close_button" >
</RelativeLayout>
<RelativeLayout
android:id="#+id/rateClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:background="#drawable/rate_now_button" />
</RelativeLayout>
</RelativeLayout>
This is what I am getting. How am i suppose to remove the dialog layout. The white big borders.
Don't use AlertDialog.Builder. Try this instead.
Dialog d = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
or
Dialog d = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
You can use whatever theme meets your criteria, or create your own. See answer to this question and this other question. See also available themes.
See Dialog for documentation on setContentView(), setCancelable(), show() and other methods you might find useful.
You can try:
myDialog.show();
Window window = myDialog.getWindow();
window.setLayout(300, 300);
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
Double width = metrics.widthPixels*.7;
Double height = metrics.heightPixels*.7;
Window win = dialog.getWindow();
win.setLayout(width.intValue(), height.intValue());
Try something like this:
dialog_item = new Dialog(Pre_Venda_Digitacao_2.this);
dialog_item.setContentView(R.layout.layout_pre_venda_digitacao_add_produto);
Util.softKeyboard(dialog_item.getWindow(), false);
// Recuperar os componentes da janela e disponibilizar para as variáveis globais.
dialog_Item_getComponentes();
/***********************OnShow do Dialog*****************************/
dialog_item.setOnShowListener(new OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
//Recupera a menor fonte dentro do layout passado
float lower_font_size = AutoResizeTextView_Functions.Get_Lower_Font_Size(ll_add_produto, 1000);
//Seta menor fonte recuparada anteriormente para os textos do layout passado
AutoResizeTextView_Functions.Resize_Text(ll_add_produto, lower_font_size);
}
});
dialog_item.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
dialog_item = null;
preVenda_Item = null;
}
});
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog_item.getWindow().getAttributes());
lp.width = (int) (width - (width * 0.07) ); //Tira 7% da largura total da tela para deixar um espaço na janela
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog_item.getWindow().setAttributes(lp);
dialog_item.show();
Do this in your rate_layout.xml:
<!-- begin snippet: js hide: false -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0000"
>
You also need to create and call a dialog Fragment if you didnt:
public class AddDialog extends DialogFragment
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.rate_layout, null));
return builder.create();
}
}
Then call the Dialog in a function:
public void SomeFunction()
{
DialogFragment d = new AddDialog();
d.show(getSupportFragmentManager(), "some_dialog_refrence");
}
we can set width, height of custom dialog like this.
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int screenHeight = displayMetrics.heightPixels;
int screenWidth = displayMetrics.widthPixels;
android.view.WindowManager.LayoutParams lp = new android.view.WindowManager.LayoutParams();
lp.copyFrom(deleteDialog.getWindow().getAttributes());
// If we need to set background color of activity
// We need to set this before calling show() method
lp.dimAmount = 0.7f;
deleteDialog.getWindow().setAttributes(lp);
deleteDialog.show();
// we need to set width, height after calling show() method
Window window = deleteDialog.getWindow();
window.setLayout(screenWidth - screenWidth/2), WindowManager.LayoutParams.WRAP_CONTENT);

Categories

Resources