Setting Window Dim only working in onCreate() - android

I have a little problem with my Window dimming.
Basically, I want to set the dimAmount of my Activity to zero as soon as I swipe it into one direction.
Please be aware that my Activity is displayed as a dialog, and can be swiped to the left or right. This works perfectly fine. But the setWindowDim() method has no effect when called after swipe.
If i call the setWindowDim inside my onCreate method, it works perfectly fine.
I have no idea why it doesnt work anywhere else.
public class FinishDialog extends Activity {
private FrameLayout frame = null;
private GestureDetector gd = null;
private int displaywidth = 0;
private int original_x = 0;
private int dialog_width = 0;
private final int POS_LEFT = -1;
private final int POS_MID = 0;
private final int POS_RIGHT = 1;
/** the dialogs current position, POS_MID on startup */
private int current_pos = POS_MID;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
frame = new FrameLayout(this);
gd = new GestureDetector(this, new TouchManager(this));
// fill the challenge layout into the framelayout
frame.addView(LayoutInflater.from(getBaseContext()).inflate(R.layout.finishdialog, null));
setContentView(frame);
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) frame.getLayoutParams();
GameLogic g = new GameLogic();
displaywidth = g.getDisplayWidth(this);
lp.width = displaywidth - displaywidth / 6;
lp.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
LinearLayout llFinish = (LinearLayout) findViewById(R.id.llFinishDialog);
LinearLayout.LayoutParams lpLL = (LinearLayout.LayoutParams) llFinish.getLayoutParams();
lp.height = lpLL.height;
frame.setLayoutParams(lp);
// setWindowDim(0.0f); ---> if i set the dim here, it works perfectly fine
original_x = (int) frame.getX();
dialog_width = lp.width;
}
private void setWindowDim(float dim) {
Log.i("FinishDialog", "Setting window dim to " + dim + ".");
WindowManager.LayoutParams lpWin = getWindow().getAttributes();
lpWin.dimAmount = dim;
getWindow().setAttributes(lpWin);
}
/**
* move the dialog, depending on the swipe direction and the
* current position of the dialog
* #param action
*/
public void interpretTouch(int action) {
switch(action) {
case TouchManager.MOVE_DIALOG_RIGHT:
if(frame != null) {
if(current_pos == POS_MID) {
swipeDialog(600, frame, 0, dialog_width, 0, 0);
current_pos = POS_RIGHT;
setWindowDim(0.0f); // here setting the dim has no effect
} else if (current_pos == POS_LEFT) {
swipeDialog(600, frame, - dialog_width, original_x, 0, 0);
current_pos = POS_MID;
setWindowDim(0.9f); // here setting the dim has no effect
} else if (current_pos == POS_RIGHT) {
// if we are on the right and swipe right, nothing happens
}
}
Log.i("Challenge", "Moving dialog to the right.");
break;
case TouchManager.MOVE_DIALOG_LEFT:
if(frame != null) {
if(current_pos == POS_MID) {
swipeDialog(600, frame, 0, -dialog_width, 0, 0);
current_pos = POS_LEFT;
setWindowDim(0.0f); // here setting the dim has no effect
} else if (current_pos == POS_LEFT) {
// if we are on the left and swipe left, nothing happens
} else if (current_pos == POS_RIGHT) {
swipeDialog(600, frame, dialog_width, original_x, 0, 0);
current_pos = POS_MID;
setWindowDim(0.9f); // here setting the dim has no effect
}
}
Log.i("Challenge", "Moving dialog to the left.");
break;
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return gd.onTouchEvent(event);
}
private void swipeDialog(int time, View framelayout, int fromDeltaX, int toDeltaX, int fromDeltaY, int toDeltaY) {
Log.i("FinishDialog", "Dialog swiped.");
TranslateAnimation trans = new TranslateAnimation(fromDeltaX, toDeltaX,
fromDeltaY, toDeltaY);
trans.setFillAfter(true);
trans.setFillEnabled(true);
trans.setDuration(time);
framelayout.startAnimation(trans);
}
}

Starting this activity right after I change the Window dim finally did the job.
Unfortunately, now the Screen flashes pretty "ugly" when the RefreshActivity gets started, does anyone have a solution for that?
import android.app.Activity;
import android.os.Bundle;
public class RefreshActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
finish();
}
}

Related

why in android mobile version 8.1 [oreo] the Floating Widget service is not working? [app is getting crushed] [duplicate]

This question already has answers here:
SYSTEM_ALERT_WINDOW PERMISSION on API 26 not working as expected. Permission denied for window type 2002
(6 answers)
Closed 3 years ago.
I was working in Floating Widget service icon ,the code is working fine till android version 6.1,i am able to get the notification icon from the server when it send the notification.
but while testing it in android version 8.1 the application getting crushed when the notification is send from the server,
but i am not able to find the solution for it.i dont have any idea why it is happening.
LOGCAT
beginning of crash
2019-03-02 11:41:21.416 12616-12616/com.progressive_solution.parttimeforce E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.progressive_solution.parttimeforce, PID: 12616
java.lang.RuntimeException: Unable to create service com.progressive_solution.parttimeforce.FloatingWidgetService: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W#ac5309 -- permission denied for window type 2002
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3568)
at android.app.ActivityThread.-wrap4(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1812)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7000)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Caused by: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W#ac5309 -- permission denied for window type 2002
at android.view.ViewRootImpl.setView(ViewRootImpl.java:1026)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:384)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:101)
at com.progressive_solution.parttimeforce.FloatingWidgetService.addRemoveView(FloatingWidgetService.java:86)
at com.progressive_solution.parttimeforce.FloatingWidgetService.onCreate(FloatingWidgetService.java:58)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3558)
at android.app.ActivityThread.-wrap4(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1812) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:7000) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408) 
MYCODE
FloatingWidgetService.java
public class FloatingWidgetService extends Service implements View.OnClickListener
{
private WindowManager mWindowManager;
private View mFloatingWidgetView, collapsedView, expandedView;
private ImageView remove_image_view;
private Point szWindow = new Point();
private View removeFloatingWidgetView;
private int x_init_cord, y_init_cord, x_init_margin, y_init_margin;
//Variable to check if the Floating widget view is on left side or in right side
// initially we are displaying Floating widget view to Left side so set it to true
private boolean isLeft = true;
public FloatingWidgetService() {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
//init WindowManager
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
getWindowManagerDefaultDisplay();
//Init LayoutInflater
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
addRemoveView(inflater);
addFloatingWidgetView(inflater);
implementClickListeners();
implementTouchListenerToFloatingWidgetView();
}
/* Add Remove View to Window Manager */
private View addRemoveView(LayoutInflater inflater) {
//Inflate the removing view layout we created
removeFloatingWidgetView = inflater.inflate(R.layout.remove_floating_widget_layout, null);
//Add the view to the window.
WindowManager.LayoutParams paramRemove = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
//Specify the view position
paramRemove.gravity = Gravity.TOP | Gravity.LEFT;
//Initially the Removing widget view is not visible, so set visibility to GONE
removeFloatingWidgetView.setVisibility(View.GONE);
remove_image_view = (ImageView) removeFloatingWidgetView.findViewById(R.id.remove_img);
//Add the view to the window
mWindowManager.addView(removeFloatingWidgetView, paramRemove);
return remove_image_view;
}
/* Add Floating Widget View to Window Manager */
private void addFloatingWidgetView(LayoutInflater inflater) {
//Inflate the floating view layout we created
mFloatingWidgetView = inflater.inflate(R.layout.activity_floating_widget_service, null);
//Add the view to the window.
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
//Specify the view position
params.gravity = Gravity.TOP | Gravity.LEFT;
//Initially view will be added to top-left corner, you change x-y coordinates according to your need
params.x = 0;
params.y = 100;
//Add the view to the window
mWindowManager.addView(mFloatingWidgetView, params);
//find id of collapsed view layout
collapsedView = mFloatingWidgetView.findViewById(R.id.collapse_view);
//find id of the expanded view layout
expandedView = mFloatingWidgetView.findViewById(R.id.expanded_container);
}
private void getWindowManagerDefaultDisplay() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
mWindowManager.getDefaultDisplay().getSize(szWindow);
else {
int w = mWindowManager.getDefaultDisplay().getWidth();
int h = mWindowManager.getDefaultDisplay().getHeight();
szWindow.set(w, h);
}
}
/* Implement Touch Listener to Floating Widget Root View */
private void implementTouchListenerToFloatingWidgetView() {
//Drag and move floating view using user's touch action.
mFloatingWidgetView.findViewById(R.id.root_container).setOnTouchListener(new View.OnTouchListener() {
long time_start = 0, time_end = 0;
boolean isLongClick = false;//variable to judge if user click long press
boolean inBounded = false;//variable to judge if floating view is bounded to remove view
int remove_img_width = 0, remove_img_height = 0;
Handler handler_longClick = new Handler();
Runnable runnable_longClick = new Runnable() {
#Override
public void run() {
//On Floating Widget Long Click
//Set isLongClick as true
isLongClick = true;
//Set remove widget view visibility to VISIBLE
removeFloatingWidgetView.setVisibility(View.VISIBLE);
onFloatingWidgetLongClick();
}
};
#Override
public boolean onTouch(View v, MotionEvent event) {
//Get Floating widget view params
WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams) mFloatingWidgetView.getLayoutParams();
//get the touch location coordinates
int x_cord = (int) event.getRawX();
int y_cord = (int) event.getRawY();
int x_cord_Destination, y_cord_Destination;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
time_start = System.currentTimeMillis();
handler_longClick.postDelayed(runnable_longClick, 600);
remove_img_width = remove_image_view.getLayoutParams().width;
remove_img_height = remove_image_view.getLayoutParams().height;
x_init_cord = x_cord;
y_init_cord = y_cord;
//remember the initial position.
x_init_margin = layoutParams.x;
y_init_margin = layoutParams.y;
return true;
case MotionEvent.ACTION_UP:
isLongClick = false;
removeFloatingWidgetView.setVisibility(View.GONE);
remove_image_view.getLayoutParams().height = remove_img_height;
remove_image_view.getLayoutParams().width = remove_img_width;
handler_longClick.removeCallbacks(runnable_longClick);
//If user drag and drop the floating widget view into remove view then stop the service
if (inBounded) {
stopSelf();
inBounded = false;
break;
}
//Get the difference between initial coordinate and current coordinate
int x_diff = x_cord - x_init_cord;
int y_diff = y_cord - y_init_cord;
//The check for x_diff <5 && y_diff< 5 because sometime elements moves a little while clicking.
//So that is click event.
if (Math.abs(x_diff) < 5 && Math.abs(y_diff) < 5) {
time_end = System.currentTimeMillis();
//Also check the difference between start time and end time should be less than 300ms
if ((time_end - time_start) < 300)
onFloatingWidgetClick();
}
y_cord_Destination = y_init_margin + y_diff;
int barHeight = getStatusBarHeight();
if (y_cord_Destination < 0) {
y_cord_Destination = 0;
} else if (y_cord_Destination + (mFloatingWidgetView.getHeight() + barHeight) > szWindow.y) {
y_cord_Destination = szWindow.y - (mFloatingWidgetView.getHeight() + barHeight);
}
layoutParams.y = y_cord_Destination;
inBounded = false;
//reset position if user drags the floating view
resetPosition(x_cord);
return true;
case MotionEvent.ACTION_MOVE:
int x_diff_move = x_cord - x_init_cord;
int y_diff_move = y_cord - y_init_cord;
x_cord_Destination = x_init_margin + x_diff_move;
y_cord_Destination = y_init_margin + y_diff_move;
//If user long click the floating view, update remove view
if (isLongClick) {
int x_bound_left = szWindow.x / 2 - (int) (remove_img_width * 1.5);
int x_bound_right = szWindow.x / 2 + (int) (remove_img_width * 1.5);
int y_bound_top = szWindow.y - (int) (remove_img_height * 1.5);
//If Floating view comes under Remove View update Window Manager
if ((x_cord >= x_bound_left && x_cord <= x_bound_right) && y_cord >= y_bound_top) {
inBounded = true;
int x_cord_remove = (int) ((szWindow.x - (remove_img_height * 1.5)) / 2);
int y_cord_remove = (int) (szWindow.y - ((remove_img_width * 1.5) + getStatusBarHeight()));
if (remove_image_view.getLayoutParams().height == remove_img_height) {
remove_image_view.getLayoutParams().height = (int) (remove_img_height * 1.5);
remove_image_view.getLayoutParams().width = (int) (remove_img_width * 1.5);
WindowManager.LayoutParams param_remove = (WindowManager.LayoutParams) removeFloatingWidgetView.getLayoutParams();
param_remove.x = x_cord_remove;
param_remove.y = y_cord_remove;
mWindowManager.updateViewLayout(removeFloatingWidgetView, param_remove);
}
layoutParams.x = x_cord_remove + (Math.abs(removeFloatingWidgetView.getWidth() - mFloatingWidgetView.getWidth())) / 2;
layoutParams.y = y_cord_remove + (Math.abs(removeFloatingWidgetView.getHeight() - mFloatingWidgetView.getHeight())) / 2;
//Update the layout with new X & Y coordinate
mWindowManager.updateViewLayout(mFloatingWidgetView, layoutParams);
break;
} else {
//If Floating window gets out of the Remove view update Remove view again
inBounded = false;
remove_image_view.getLayoutParams().height = remove_img_height;
remove_image_view.getLayoutParams().width = remove_img_width;
onFloatingWidgetClick();
}
}
layoutParams.x = x_cord_Destination;
layoutParams.y = y_cord_Destination;
//Update the layout with new X & Y coordinate
mWindowManager.updateViewLayout(mFloatingWidgetView, layoutParams);
return true;
}
return false;
}
});
}
private void implementClickListeners() {
mFloatingWidgetView.findViewById(R.id.close_floating_view).setOnClickListener(this);
mFloatingWidgetView.findViewById(R.id.close_expanded_view).setOnClickListener(this);
mFloatingWidgetView.findViewById(R.id.open_activity_button).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.close_floating_view:
//close the service and remove the from from the window
stopSelf();
break;
case R.id.close_expanded_view:
collapsedView.setVisibility(View.VISIBLE);
expandedView.setVisibility(View.GONE);
break;
case R.id.open_activity_button:
//open the activity and stop service
Intent intent = new Intent(FloatingWidgetService.this, Get_Permission.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
//close the service and remove view from the view hierarchy
stopSelf();
break;
}
}
/* on Floating Widget Long Click, increase the size of remove view as it look like taking focus */
private void onFloatingWidgetLongClick() {
//Get remove Floating view params
WindowManager.LayoutParams removeParams = (WindowManager.LayoutParams) removeFloatingWidgetView.getLayoutParams();
//get x and y coordinates of remove view
int x_cord = (szWindow.x - removeFloatingWidgetView.getWidth()) / 2;
int y_cord = szWindow.y - (removeFloatingWidgetView.getHeight() + getStatusBarHeight());
removeParams.x = x_cord;
removeParams.y = y_cord;
//Update Remove view params
mWindowManager.updateViewLayout(removeFloatingWidgetView, removeParams);
}
/* Reset position of Floating Widget view on dragging */
private void resetPosition(int x_cord_now) {
if (x_cord_now <= szWindow.x / 2) {
isLeft = true;
moveToLeft(x_cord_now);
} else {
isLeft = false;
moveToRight(x_cord_now);
}
}
/* Method to move the Floating widget view to Left */
private void moveToLeft(final int current_x_cord) {
final int x = szWindow.x - current_x_cord;
new CountDownTimer(500, 5) {
//get params of Floating Widget view
WindowManager.LayoutParams mParams = (WindowManager.LayoutParams) mFloatingWidgetView.getLayoutParams();
public void onTick(long t) {
long step = (500 - t) / 5;
mParams.x = 0 - (int) (current_x_cord * current_x_cord * step);
//If you want bounce effect uncomment below line and comment above line
// mParams.x = 0 - (int) (double) bounceValue(step, x);
//Update window manager for Floating Widget
mWindowManager.updateViewLayout(mFloatingWidgetView, mParams);
}
public void onFinish() {
mParams.x = 0;
//Update window manager for Floating Widget
mWindowManager.updateViewLayout(mFloatingWidgetView, mParams);
}
}.start();
}
/* Method to move the Floating widget view to Right */
private void moveToRight(final int current_x_cord) {
new CountDownTimer(500, 5) {
//get params of Floating Widget view
WindowManager.LayoutParams mParams = (WindowManager.LayoutParams) mFloatingWidgetView.getLayoutParams();
public void onTick(long t) {
long step = (500 - t) / 5;
mParams.x = (int) (szWindow.x + (current_x_cord * current_x_cord * step) - mFloatingWidgetView.getWidth());
//If you want bounce effect uncomment below line and comment above line
// mParams.x = szWindow.x + (int) (double) bounceValue(step, x_cord_now) - mFloatingWidgetView.getWidth();
//Update window manager for Floating Widget
mWindowManager.updateViewLayout(mFloatingWidgetView, mParams);
}
public void onFinish() {
mParams.x = szWindow.x - mFloatingWidgetView.getWidth();
//Update window manager for Floating Widget
mWindowManager.updateViewLayout(mFloatingWidgetView, mParams);
}
}.start();
}
/* Get Bounce value if you want to make bounce effect to your Floating Widget */
private double bounceValue(long step, long scale) {
double value = scale * java.lang.Math.exp(-0.055 * step) * java.lang.Math.cos(0.08 * step);
return value;
}
/* Detect if the floating view is collapsed or expanded */
private boolean isViewCollapsed() {
return mFloatingWidgetView == null || mFloatingWidgetView.findViewById(R.id.collapse_view).getVisibility() == View.VISIBLE;
}
/* return status bar height on basis of device display metrics */
private int getStatusBarHeight() {
return (int) Math.ceil(25 * getApplicationContext().getResources().getDisplayMetrics().density);
}
/* Update Floating Widget view coordinates on Configuration change */
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getWindowManagerDefaultDisplay();
WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams) mFloatingWidgetView.getLayoutParams();
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (layoutParams.y + (mFloatingWidgetView.getHeight() + getStatusBarHeight()) > szWindow.y) {
layoutParams.y = szWindow.y - (mFloatingWidgetView.getHeight() + getStatusBarHeight());
mWindowManager.updateViewLayout(mFloatingWidgetView, layoutParams);
}
if (layoutParams.x != 0 && layoutParams.x < szWindow.x) {
resetPosition(szWindow.x);
}
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
if (layoutParams.x > szWindow.x) {
resetPosition(szWindow.x);
}
}
}
/* on Floating widget click show expanded view */
private void onFloatingWidgetClick() {
if (isViewCollapsed()) {
//When user clicks on the image view of the collapsed layout,
//visibility of the collapsed layout will be changed to "View.GONE"
//and expanded view will become visible.
collapsedView.setVisibility(View.GONE);
expandedView.setVisibility(View.VISIBLE);
}
}
#Override
public void onDestroy() {
super.onDestroy();
/* on destroy remove both view from window manager */
if (mFloatingWidgetView != null)
mWindowManager.removeView(mFloatingWidgetView);
if (removeFloatingWidgetView != null)
mWindowManager.removeView(removeFloatingWidgetView);
}
}
Permissioncheck.java
private void writeCalendarEvent()
{
Log.d(Utils.LogTag, "lst_StartService -> Utils.canDrawOverlays(Main.this): " + Utils.canDrawOverlays(Permissioncheck.this));
if(Utils.canDrawOverlays(Permissioncheck.this))
{
checkPermission_Contact();
startService();
}
else
{
requestPermission(OVERLAY_PERMISSION_REQ_CODE_CHATHEAD);
}
}
public void startService()
{
boolean results = checkPermission_Contact();
if (results)
{
Intent k = new Intent(context, Login.class);
startActivity(k);
}
}
private void needPermissionDialog(final int requestCode)
{
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Permissioncheck.this);
builder.setMessage("You need to allow permission");
builder.setPositiveButton("OK",
new android.content.DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
requestPermission(requestCode);
}
});
builder.setNegativeButton("Cancel", new android.content.DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
});
builder.setCancelable(false);
builder.show();
}
#Override
protected void onResume()
{
// TODO Auto-generated method stub
super.onResume();
}
private void requestPermission(int requestCode)
{
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, requestCode);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == OVERLAY_PERMISSION_REQ_CODE_CHATHEAD)
{
if (!Utils.canDrawOverlays(Permissioncheck.this))
{
needPermissionDialog(requestCode);
} else
{
startService();
}
}
}
Help me to fix the problem.
add WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
reference

ANDROID: changing navigation bar from transparent to black color

I have this slider which is an overlay view. It appears over the navigationbar when it below the screen.
normal
When a chrome browser is opened, it turns navigationbar to black and the rest works fine.
in browser
I want to achieve this effect permanetly for the navigationbar while the slider is running
The code overlay slider is here
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.sleepycoat.tapxicon.utils.ScreenUtils;
import java.security.InvalidAlgorithmParameterException;
import static android.view.MotionEvent.ACTION_OUTSIDE;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
import static android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
import static android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
import static android.view.WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN;
import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;
import static android.view.WindowManager.LayoutParams.TYPE_PHONE;
/**
* Created by egslava on 24/08/16.
* Unfortunately, Android system is not supported (or I could find how) managing keyboard in windows
* (not activities) that are always on top. So we need to manage keyboard manually.
*/
public class TopScreenDrawerLogic {
private static final String TAG = "TopScreenDrawerLogic";
final Keyboarder keyboarder;
// private final View fakeFocus;
View visibleView;
DrawerView drawer;
ScrollerLogic scroller;
private final ScreenUtils utils;
private final WindowManager wm;
public static final int COMMON_WINDOW_FLAGS =
FLAG_LAYOUT_NO_LIMITS | // for fast "resizing". Window can be moved out of screen
FLAG_NOT_TOUCH_MODAL | // other windows (on the background, that our window is not overlapped) can intercept touch events
FLAG_LAYOUT_IN_SCREEN; // need for right positioning (getting into account status bar)
// when FLAG_LAYOUT_IN_SCREEN is set getHeight() will return value - navigation bar height
public static final int BACKGROUND_WINDOW_FLAGS = COMMON_WINDOW_FLAGS |
FLAG_NOT_FOCUSABLE | FLAG_ALT_FOCUSABLE_IM; // "back" and other hardware buttons will go throw window
public static final int FOREGROUND_WINDOW_FLAGS = COMMON_WINDOW_FLAGS |
// FLAG_LOCAL_FOCUS_MODE |
// FLAG_NOT_TOUCHABLE | // if we want go clicks throw the window
FLAG_WATCH_OUTSIDE_TOUCH; // need to know when user touched outside of window to "unfocus"
private final InputMethodManager imm;
public static WindowManager.LayoutParams createLayout() {
return new WindowManager.LayoutParams(
MATCH_PARENT, MATCH_PARENT, TYPE_PHONE, FOREGROUND_WINDOW_FLAGS, PixelFormat.TRANSLUCENT);
}
//////////////////////////////////////////////////////
// mrtndat add 9/9
//////////////////////////////////////////////////////
public static WindowManager.LayoutParams createLayout(Context context) {
// int w
Point navBarSize = ScreenUtils.getNavigationBarSize(context);
Point screenSize = ScreenUtils.getRealScreenSize(context);
int maxHeight = navBarSize != null ? (screenSize.y - navBarSize.y) :
screenSize.y;
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.TRANSLUCENT);
// params.gravity = Gravity.TOP;
// params.x = 0;
// int diff = 0;
// if (navBarSize != null) {
// diff = maxHeight - navBarSize.y;
// }
// if (navBarSize != null) {
// params.y = -navBarSize.y+144;
// }
return params;
}
//////////////////////////////////////////////////////
// mrtndat end 9/9
//////////////////////////////////////////////////////
public TopScreenDrawerLogic(DrawerView drawer, View visibleView) {
this.visibleView = visibleView;
this.drawer = drawer;
scroller = new ScrollerLogic(drawer);
keyboarder = new Keyboarder(drawer);
utils = new ScreenUtils(drawer.getContext());
wm = drawer.windowManager;
imm = (InputMethodManager) drawer.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
// this.fakeFocus = fakeFocus;
}
public int minY() {
return 0;
}
public int maxY() {
int[] location = new int[2];
visibleView.getLocationInWindow(location);
int visibleViewTop = location[1];
ViewGroup.MarginLayoutParams margins = (ViewGroup.MarginLayoutParams) visibleView.getLayoutParams();
int visibleViewBottom = visibleViewTop + visibleView.getHeight() + margins.bottomMargin; //just a bit margin;
return utils.getDisplayHeight() - visibleViewBottom;// - navBarHeight;
}
private int minY(int value) {
return Math.max(value, minY());
}
private int maxY(int value) {
return Math.min(maxY(), value);
}
;
public int boundY(int y) {
return maxY(minY(y));
}
// difference between nearest correct Y value and given
public int yCorrection(int y) {
return y - boundY(y);
}
public int shiftDrawer(int dy) {
return shiftDrawer(dy, false);
}
/**
* shifts drawer and returns new y coordinate
*/
public int shiftDrawer(int dy, boolean animated) {
WindowManager.LayoutParams params = drawer.getLayoutParams();
WindowManager wm = drawer.windowManager;
// params.y = params.y + dy;
if (dy > 1500) {
new Throwable().printStackTrace();
}
final int newY = drawer.logic.boundY(params.y + dy);
if (animated) {
new TranslateDrawerAnim(drawer, boundY(drawer.getLayoutParams().y + (int) dy)/* target layout height */, 250).execute();
} else {
params.y = newY;
wm.updateViewLayout(drawer, params);
}
return params.y;
}
public int shiftDrawerByScreenPercent(float dy, boolean animated) {
return shiftDrawer((int) (utils.getDisplayHeight() / 100.0f * dy), animated);
}
public static final int STATE_UNDEFINED = 0;
public static final int STATE_FOREGROUND = 1;
public static final int STATE_BACKGROUND = 2;
public static final int INITIAL_STATE = STATE_FOREGROUND;
public int state = INITIAL_STATE;
public void resetState(View focusedView) {
if (INITIAL_STATE == STATE_BACKGROUND) {
makeBackground();
} else if (INITIAL_STATE == STATE_FOREGROUND) {
makeForeground();
} else throw new RuntimeException(new InvalidAlgorithmParameterException("Strange state"));
}
public void makeBackground() {
new Throwable().printStackTrace();
Log.d(TAG, "makeBackground()" + ", previous state = " + stateToString(state));
if (state == STATE_BACKGROUND) return;
state = STATE_BACKGROUND;
imm.hideSoftInputFromWindow(drawer.getWindowToken(), 0);
WindowManager.LayoutParams params = drawer.getLayoutParams();
WindowManager wm = drawer.windowManager;
params.softInputMode = SOFT_INPUT_STATE_ALWAYS_HIDDEN;
params.flags = BACKGROUND_WINDOW_FLAGS;
wm.updateViewLayout(drawer, params);
// final View focus = drawer.findFocus();
// if (focus != null) focus.postDelayed(new Runnable() {
// #Override
// public void run() {
// imm.hideSoftInputFromWindow(drawer.getWindowToken(), 0, new ResultReceiver(new Handler(new Handler.Callback() {
// #Override
// public boolean handleMessage(Message message) {
// fakeFocus.requestFocus();
// keyboarder.applyPos();
// return true;
// }
// })));
// }
// }, 250);
}
public String stateToString(int state) {
switch (state) {
case STATE_BACKGROUND:
return "background";
case STATE_FOREGROUND:
return "foreground";
default:
throw new RuntimeException("Invalid state");
}
}
public void makeForeground() {
new Throwable().printStackTrace();
Log.d(TAG, "makeForeground()" + ", previous state = " + stateToString(state));
if (state == STATE_FOREGROUND) return;
state = STATE_FOREGROUND;
WindowManager.LayoutParams params = drawer.getLayoutParams();
WindowManager wm = drawer.windowManager;
params.flags = FOREGROUND_WINDOW_FLAGS;
// params.softInputMode = SOFT_INPUT_STATE_UNCHANGED;
params.softInputMode = SOFT_INPUT_STATE_HIDDEN;
// params.softInputMode = SOFT_INPUT_STATE_VISIBLE;
wm.updateViewLayout(drawer, params);
// request focus on focused element. Why? The reason:
// 1. when window is in background state it can't be focused.
// 2. when window is in foreground state some time it focuses last focused element
// 3. when this happens Android shows keyboard but DOESN'T call onFocusChanged
// 4. #Keyboarder class can't process this case correctly and move drawer on keyboard level
// final View focus = drawer.findFocus();
// if (focus != null)focus.postDelayed(new Runnable() {
// #Override
// public void run() {
// focus.requestFocus();
// }
// }, 250);
}
public void dispatchTouchEvent(MotionEvent e) {
Log.d(TAG, "dispatchTouchEvent() called with: " + "e = [" + e + "]");
switch (e.getAction()) {
case ACTION_OUTSIDE:
makeBackground();
break;
default:
makeForeground();
break;
}
}
public boolean delegateOnTouch(MotionEvent e) {
Log.d(TAG, "delegateOnTouch() called with: " + "e = [" + e + "]");
keyboarder.delegateOnTouch(e);
return scroller.delegateOnTouch(e);
}
// need to process keyboard by ourselves
public void delegateOnInputClick(final View v) {
keyboarder.delegateOnInputClick(v);
}
public void delegateOnInputFocus(final View v, final boolean b) {
keyboarder.delegateOnInputFocus(v, b);
}
public boolean delegateOnInterceptTouch(MotionEvent e) {
return scroller.delegateOnInterceptTouch(e);
}
public void callWhenEnterIsPressed() {
}
public void callWhenKeypressed() { // for backpressing
}
public void callWhenKeyboardIsShown() {
}
public void delegateOnKeyPreIme(int keyCode, KeyEvent event) {
keyboarder.delegateOnKeyPreIme(keyCode, event);
}
}
I want to achieve this affect of chrome browser by using Transparent activity with the overlay layout but again the slider appear over the the transparent activity.

How can I fire a trigger to click when using slider in android?

I am using Slider like gmail or Facbook in android this is fine. What i have done is i just created a new activity and given animation to it so it looks like slider. Now what i want is when user click any button in slider a new activity should open and perform task what i specify in it. But i am not getting how to pass click event in slider.
My code
public class PlayAudio extends Activity implements OnCompletionListener,
SeekBar.OnSeekBarChangeListener {
boolean alreadyShowing = false;
private int windowWidth;
private int windowHeight;
private PopupWindow fadePopup;
private Animation ta;
private RelativeLayout baseView;
LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
Display display = getWindowManager().getDefaultDisplay();
windowWidth = display.getWidth();
windowHeight = display.getHeight();
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
findViewById(R.id.imageView1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!alreadyShowing) {
alreadyShowing = true;
openSlidingMenu();
}
}
});
findViewById(R.id.imageView3).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!alreadyShowing) {
alreadyShowing = true;
openSlidingMenu();
}
}
});
}
private void openSlidingMenu() {
showFadePopup();
int width = (int) (windowWidth * 0.8f);
translateView((float) (width));
#SuppressWarnings("deprecation")
int height = LayoutParams.FILL_PARENT;
// creating a popup
final View layout = inflater.inflate(R.layout.option_popup_layout,
(ViewGroup) findViewById(R.id.popup_element));
final PopupWindow optionsPopup = new PopupWindow(layout, width, height,
true);
optionsPopup.setBackgroundDrawable(new PaintDrawable());
optionsPopup.showAtLocation(layout, Gravity.NO_GRAVITY, 0, 0);
optionsPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
public void onDismiss() {
// Removing the fade effect
fadePopup.dismiss();
// to clear the previous animation transition in
cleanUp();
// move the view out
translateView(0);
// to clear the latest animation transition out
cleanUp();
// resetting the variable
alreadyShowing = false;
}
});
}
private void showFadePopup() {
final View layout = inflater.inflate(R.layout.fadepopup,
(ViewGroup) findViewById(R.id.fadePopup));
fadePopup = new PopupWindow(layout, windowWidth, windowHeight, false);
fadePopup.showAtLocation(layout, Gravity.NO_GRAVITY, 0, 0);
}
private void translateView(float right) {
ta = new TranslateAnimation(0f, right, 0f, 0f);
ta.setDuration(100);
ta.setFillEnabled(true);
ta.setFillAfter(true);
baseView = (RelativeLayout) findViewById(R.id.Player_Slider);
baseView.startAnimation(ta);
baseView.setVisibility(View.VISIBLE);
}
private void cleanUp() {
if (null != baseView) {
baseView.clearAnimation();
baseView = null;
}
if (null != ta) {
ta.cancel();
ta = null;
}
fadePopup = null;
}
}
Here in click event i am calling openSlidingMenu function which open's new activity option_popup_layout (http://i.share.pho.to/fb125f6f_o.png)
Now what i want is when i click any of the image in option_popup_layout a new activity should open and i want perform some operation over there but i am not getting where i have to use click event to call new activity.
I have tried some piece of code to put click event inside creating function as well as other method too but not getting work.
Please help me to solve this. Thanks in advance.

Animate view sliding out of another view, pushing views below out of the way

I have a list of buttons. When I press a button, a View should slide in a downwards motion out of the button, like this:
Start:
Halfway:
End:
How would I go about this? The View that should slide out is bigger than the button, so first hiding the View behind the button and then sliding it downwards causes the View to be visible above the button. That should not happen.
Any ideas or examples on how to approach this?
I believe the simplest approach is to extend Animation class and override applyTransformation() to change the view's height as follows:
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.LinearLayout;
public class MyCustomAnimation extends Animation {
public final static int COLLAPSE = 1;
public final static int EXPAND = 0;
private View mView;
private int mEndHeight;
private int mType;
private LinearLayout.LayoutParams mLayoutParams;
public MyCustomAnimation(View view, int duration, int type) {
setDuration(duration);
mView = view;
mEndHeight = mView.getHeight();
mLayoutParams = ((LinearLayout.LayoutParams) view.getLayoutParams());
mType = type;
if(mType == EXPAND) {
mLayoutParams.height = 0;
} else {
mLayoutParams.height = LayoutParams.WRAP_CONTENT;
}
view.setVisibility(View.VISIBLE);
}
public int getHeight(){
return mView.getHeight();
}
public void setHeight(int height){
mEndHeight = height;
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
if (interpolatedTime < 1.0f) {
if(mType == EXPAND) {
mLayoutParams.height = (int)(mEndHeight * interpolatedTime);
} else {
mLayoutParams.height = (int) (mEndHeight * (1 - interpolatedTime));
}
mView.requestLayout();
} else {
if(mType == EXPAND) {
mLayoutParams.height = LayoutParams.WRAP_CONTENT;
mView.requestLayout();
}else{
mView.setVisibility(View.GONE);
}
}
}
}
To use it, set your onclick() as follows:
int height;
#Override
public void onClick(View v) {
if(view2.getVisibility() == View.VISIBLE){
MyCustomAnimation a = new MyCustomAnimation(view2, 1000, MyCustomAnimation.COLLAPSE);
height = a.getHeight();
view2.startAnimation(a);
}else{
MyCustomAnimation a = new MyCustomAnimation(view2, 1000, MyCustomAnimation.EXPAND);
a.setHeight(height);
view2.startAnimation(a);
}
}
Regards.
Use something like:
Animation a = new ScaleAnimation(1, 1, 0, 1, Animation.RELATIVE_TO_SELF, (float) 0.5, Animation.RELATIVE_TO_SELF, (float) 0);
a.setFillAfter(true);
view.setAnimation(a);
a.setDuration(1000);
view.startAnimation(a);
Here is simple example of hand-made animation, that provide what you want. It works in test app, but I'm not sure that there is no bugs:
public class MainActivity extends Activity implements OnClickListener {
private Timer timer;
private TimerTask animationTask;
private View view1;
private View view2;
boolean animating;
boolean increasing = true;
int initHeight = -1;
private LayoutParams params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = new Timer();
view1 = findViewById(R.id.view1);// clickable view
view1.setOnClickListener(this);
view2 = findViewById(R.id.view2);// animated view
params = view2.getLayoutParams();
}
#Override
protected void onDestroy() {
super.onDestroy();
timer.cancel();
}
#Override
public void onClick(View v) {
Toast.makeText(this, "start animating...", Toast.LENGTH_SHORT).show();
animationTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (animationFinished()) {
animating = false;
cancel();//canceling animating task
return;
}
params.height += increasing ? 1 : -1;
view2.setLayoutParams(params);
}
});
}
private boolean animationFinished() {
int viewHeight = view2.getHeight();
if (increasing && viewHeight >= initHeight) {
return true;
}
if (!increasing && viewHeight <= 0) {
return true;
}
return false;
}
};
//if we already animating - we just change direction of animation
increasing = !increasing;
if (!animating) {
animating = true;
int height = view2.getHeight();
params.height = height;
view2.setLayoutParams(params);//change param "height" from "wrap_conent" to real height
if (initHeight < 0) {//height of view - we setup it only once
initHeight = height;
}
timer.schedule(animationTask, 0, 10);//changing repeat time here will fasten or slow down animation
}
}
}
Maybe you can set the height to 0 and gradually increase the height. But then you will have the problem that you have to be sure your text is aligned at the bottom of the view. And also to know what the maximal height of the view should be.
use a sliding list adapter so much easier than messing around with animations
https://github.com/tjerkw/Android-SlideExpandableListView
Simply pass android:animateLayoutChanges to LinearLayout that holds all the views, you will achieve your desired result.
I would do it like that. First the layout for the whole collapsible panel component: (pseudo xml)
RelativeLayout (id=panel, clip)
LinearLayout (id=content, alignParentBottom=true)
LinearLayout (id=handle, above=content)
This should ensure that the content is always below the handle.
Then when you need to collapse:
Animate the top margin of content from 0 to -content.height
Animate the height of the panel from current to current-content.height

Android Gallery freezes screen until scrolled

I have a full-screen custom Gallery. Elements of the gallery have buttons and other interactive areas. Some user interface is done through dialog boxes that pop in front of the gallery; when a dialog box is dismissed, the user is taken back to the gallery.
Most of the time, this works fine. However, sometimes, after a dialog box is dismissed, the buttons stop taking user input. The gallery, on the other hand, still scrolls. What's even more bizarre, as soon as I scroll the gallery, the system processes those clicks I thought failed (pops up a dialog, etc.).
It is easy to say that the main UI thread is locked. Why is it locked? How do I unlock it? Any help will be appreciated. Below is the full code of the class.
UPDATE. One of the elements within the Gallery is a HorizontalScrollView. When I try scroll it, mouse messages come through; I stepped through them and saw that the scrollBy() and invalidate() are properly called. Then I printed out the message queue. The only event that passes through the main loop is 1006, which I assume is the Touch event. The Draw event, the 1000, never makes it. Once I scroll the Gallery back and forth -- lo and behold -- the message queue starts receiving the 1000's, so the HorizontalScrollView scrolls fine!
So the question becomes: what stops the Draw events, and how do I make sure they are sent to the queue?
public class PlayerGallery extends Gallery
{
// 4 buttons to display
private final static int BUT_BIRD = 0;
private final static int BUT_SCORE = 1;
private final static int BUT_ROUND = 2;
private final static int BUT_MOVE = 3;
private final static int N_BUTTONS = 4;
// button images
private final static Drawable[] imgButtons =
{
WonDraw.WW.bird,
WonDraw.WW.scores,
WonDraw.WW.moveSumm,
WonDraw.WW.lastMove,
};
// individual player views
private PlayerView[] views;
// card that was clicked in the current player view
private Card clickedCard = null;
// wonder that was clicked in the current player view
private Player clickedWonderPlayer = null;
// one player
private final class PlayerView extends RelativeLayout
implements OnClickListener
{
// base view ID for the buttons
private final static int BUT_VIEW_ID = 200;
// player to display
final Player player;
// drawing data
private PlayerDisplay pd = null;
// the sub-view on top that shows player's hand
private HandView handView = null;
// button that takes user into bird's view
private final GlassButton[] buttons = new GlassButton[N_BUTTONS];
public PlayerView(Player player)
{
super(WonActivity.W.getApplicationContext());
setBackgroundColor(Color.TRANSPARENT);
this.player = player;
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
lp.addRule(ALIGN_PARENT_TOP);
handView = new HandView();
addView(handView, lp);
for (int i = 0; i < buttons.length; ++i)
{
lp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (i % 2 == 0)
lp.addRule(ALIGN_PARENT_RIGHT);
else
lp.addRule(LEFT_OF, buttons[i - 1].getId());
lp.addRule(BELOW, i / 2 == 0 ? handView.getId() : buttons[i - 2].getId());
GlassButton but = new ImgGlassButton(GlassButton.ROUND, imgButtons[i]);
but.setId(BUT_VIEW_ID + i);
but.setOnClickListener(this);
buttons[i] = but; addView(but, lp);
}
}
// reset for the next player
void reset(boolean useBigCards)
{
pd = WonActivity.W.getDisplay(player.id, useBigCards);
if (useBigCards)
{
handView.pd = pd;
handView.hand = WonActivity.W.getCurrentHand();
handView.setVisibility(VISIBLE);
handView.requestLayout();
handView.scrollTo(0, 0);
}
else
{
handView.pd = null;
handView.hand = null;
handView.setVisibility(GONE);
}
for (int i = BUT_ROUND; i <= BUT_MOVE; ++i)
buttons[i].setEnabled(Table.T.movesAvailable());
invalidate();
}
#Override
protected void dispatchSetPressed(boolean pressed)
{
// if I don't do that, bird button gets pressed when I scroll the gallery!
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
int x = (int)event.getX();
int y = (int)event.getY();
clickedCard = pd.findSmallCard(x, y);
clickedWonderPlayer = clickedCard == null && pd.isInWonder(x, y) ?
player : null;
}
return super.onTouchEvent(event);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(MeasureSpec.makeMeasureSpec(WonActivity.W.getWidth() - 2, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(WonActivity.W.getHeight(), MeasureSpec.EXACTLY));
setBackgroundColor(Color.TRANSPARENT);
setBackgroundDrawable(WonDraw.W.getWood());
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
if (pd == null) return;
canvas.save();
pd.draw(canvas, handView.hand, true);
canvas.restore();
}
public void onClick(View v)
{
switch (v.getId() - BUT_VIEW_ID)
{
case BUT_BIRD:
WonActivity.W.switchToBird(player.id);
break;
case BUT_SCORE:
WonActivity.W.showScoreDlg();
break;
case BUT_ROUND:
WonActivity.W.showRoundDlg();
break;
case BUT_MOVE:
break;
}
}
};
// custom adapter for the gallery: provides circular functionality
private class PGAdapter extends BaseAdapter
{
public int getCount()
{
return Integer.MAX_VALUE;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
return views[position % views.length];
}
};
public PlayerGallery()
{
super(WonActivity.W.getApplicationContext());
setSpacing(0);
setBackgroundColor(Color.TRANSPARENT);
views = new PlayerView[Table.T.getPlayerCount()];
for (int i = 0; i < Table.T.getPlayerCount(); ++i)
views[i] = new PlayerView(Table.T.getPlayer(i));
setAdapter(new PGAdapter());
setHorizontalFadingEdgeEnabled(false);
setVerticalFadingEdgeEnabled(false);
}
// reset for the next player
void changeMovingPlayer()
{
for (int i = 0; i < views.length; ++i)
views[i].reset(i == WonActivity.W.getCurrentPlayerID());
setViewedPlayer(Math.max(WonActivity.W.getCurrentPlayerID(), 0));
}
// set the player whose buildings to view
void setViewedPlayer(int index)
{
int pos = Integer.MAX_VALUE / 2;
pos -= pos % views.length;
setSelection(pos + index);
views[index].requestFocus();
views[index].invalidate();
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
int kEvent = e2.getX() > e1.getX() ?
KeyEvent.KEYCODE_DPAD_LEFT :
KeyEvent.KEYCODE_DPAD_RIGHT;
onKeyDown(kEvent, null);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
boolean b = super.onTouchEvent(event);
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_UP:
if (event.getEventTime() - event.getDownTime() < WonActivity.CLICK_MS)
{
if (clickedCard != null)
WonActivity.W.showCardDlg(clickedCard);
else if (clickedWonderPlayer != null)
WonActivity.W.showWonderDlg(clickedWonderPlayer);
}
clickedCard = null;
clickedWonderPlayer = null;
break;
}
return b;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int w = MeasureSpec.getSize(widthMeasureSpec);
int h = MeasureSpec.getSize(heightMeasureSpec);
WonActivity.W.resize(w, h);
super.onMeasure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY));
}
}

Categories

Resources