English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Recientemente, se ha surgido una nueva necesidad, en la página se muestra una ventana flotante y es clickable, la implementación del código es la siguiente:
Implementar la imagen flotante en Activity:
@Override public void onResume() { super.onResume(); createView(); } @Override public void onPause() { super.onPause(); / Destruir la ventana flotante al salir del programa (destrucción de Activity) if(floatView!=null && windowManager !=null) { windowManager.removeView(floatView); floatView=null; windowManager = null; windowManagerParams = null; }} private void createView() { if(floatView!=null) return ; CmsAPI cmsAPI = RestAdapterUtils.getRestAPI(Config.NEW_CMS_URL, CmsAPI.class, this); cmsAPI.getFloatingAd(new Callback<AdFloating>() {//Solicitar datos @Override public void success(AdFloating adFloating, Response response) {}} if (adFloating != null && "0".equals(adFloating.getErrorCode())) { long startTime = adFloating.getStarttime(); long endTime = adFloating.getEndtime(); long currentTime = System.currentTimeMillis(); // LOGD(startTime + " +++++ "+endTime +" "+currentTime +" "+(currentTime > startTime && currentTime < endTime)); if (currentTime > startTime && currentTime < endTime) {//El período de validez de la actividad floatView = new FloatView(getApplicationContext()); floatView.setOnClickListener(MainActivity.this); int height = 240; int width = 110; float ratio= 1.35f; if (!TextUtils.isEmpty(adFloating.getImg2)) { try { height = Integer.parseInt(adFloating.getImg2h()); width = Integer.parseInt(adFloating.getImg2w()); ratio = (float) width / height; } catch (Exception e) { ratio = 1.35f; } } // floatView.setAspectRatio(ratio);//El tamaño de la imagen floatView.setImageURI(Uri.parse(adFloating.getImg2));//Configurar la dirección de red de la imagen // floatView.setImageResource(R.drawable.face_icon); // Aquí se realiza una demostración simple utilizando el icono integrado // Get WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE); // Set parameters related to LayoutParams (global variables) windowManagerParams = ((MiGuApplication) getApplication()).getWindowParams(); windowManagerParams.type = WindowManager.LayoutParams.TYPE_PHONE; // Set window type windowManagerParams.format = PixelFormat.RGBA_8888; // Set image format, with the effect of background transparency // Set Window flag windowManagerParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; /* * Note that the value of flag can be: * LayoutParams.FLAG_NOT_TOUCH_MODAL does not affect subsequent events * LayoutParams.FLAG_NOT_FOCUSABLE not focusable * LayoutParams.FLAG_NOT_TOUCHABLE not touchable */ // Adjust the floating window to the top-left corner for easy adjustment of coordinates windowManagerParams.gravity = Gravity.LEFT | Gravity.TOP; // Establish the initial values of x and y with the top-left corner of the screen as the origin DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int screenWidth = dm.widthPixels; int screenHeigh = dm.heightPixels; int x = screenWidth - SystemTools.dip2px(MainActivity.this, 100); int y= screenHeigh - SystemTools.dip2px(MainActivity.this, 200); windowManagerParams.x = x; windowManagerParams.y = y; // Establecer los datos de altura y anchura de la ventana flotante windowManagerParams.width = width;//Establecer el ancho de la ventana como el tamaño de la imagen windowManagerParams.height = height;//Establecer la altura de la ventana como el tamaño de la imagen // windowManagerParams.width = WindowManager.LayoutParams.WRAP_CONTENT; // windowManagerParams.height = WindowManager.LayoutParams.WRAP_CONTENT; // Mostrar la imagen de myFloatView windowManager.addView(floatView, windowManagerParams); return; } } } @Override public void failure(RetrofitError error) {//Falla en la solicitud de datos de red LOGE(error.getMessage()); } }); } public void onClick(View v) {//Evento de clic en la imagen Intent intent = new Intent(MainActivity.this, ActivitiesDetails.class); startActivity(intent); }
Controlador de imagen:
public class FloatView extends SimpleDraweeView { private float mTouchX; private float mTouchY; private float x; private float y; private float mStartX; private float mStartY; private OnClickListener mClickListener; private WindowManager windowManager = (WindowManager) getContext(); .getApplicationContext().getSystemService(Context.WINDOW_SERVICE); // esta variable windowManagerParams es la variable global obtenida, utilizada para guardar las propiedades de la ventana flotante private WindowManager.LayoutParams windowManagerParams = ((MiGuApplication) getContext() .getApplicationContext()).getWindowParams(); public FloatView(Context context) { super(context); } public FloatView(Context context, AttributeSet attrs) { super(context, attrs); } private long curtime=0; @Override public boolean onTouchEvent(MotionEvent event) { //obtener la altura de la barra de estado Rect frame = new Rect(); getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; System.out.println("statusBarHeight:")+statusBarHeight); // obtener las coordenadas relativas a la pantalla, es decir, con el extremo superior izquierdo de la pantalla como punto de origen x = event.getRawX(); y = event.getRawY() - statusBarHeight; // statusBarHeight es la altura de la barra de estado del sistema switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // capturar el movimiento de pulsación del dedo táctil // obtener las coordenadas relativas al View, es decir, con el extremo superior izquierdo de este View como punto de origen mTouchX = event.getX(); mTouchY = event.getY(); mStartX = x; mStartY = y; break; case MotionEvent.ACTION_MOVE: // capturar el movimiento de desplazamiento del dedo táctil updateViewPosition(); curtime=System.currentTimeMillis(); break; case MotionEvent.ACTION_UP: // capturar el movimiento de separación del dedo táctil // if(System.currentTimeMillis())-curtime>}100){ // break; // } updateViewPosition(); mTouchX = mTouchY = 0; if (Math.abs(x - mStartX) < 5 && Math.abs(y - mStartY) < 5) {//Ligero arrastre se considera un clic if(mClickListener!=null) { mClickListener.onClick(this); } } break; } return true; } @Override public void setOnClickListener(OnClickListener l) { this.mClickListener = l; } private void updateViewPosition() { // Actualizar parámetros de posición de ventana flotante windowManagerParams.x = (int) (x - mTouchX); windowManagerParams.y = (int) (y - mTouchY); windowManager.updateViewLayout(this, windowManagerParams); // Actualizar visualización } }
Esto es todo el contenido de este artículo, esperamos que ayude a su aprendizaje y que todos nos apoyen y clamemos por el tutorial.
Declaración: El contenido de este artículo se obtiene de la red, pertenece al propietario original, el contenido se contribuye y carga espontáneamente por los usuarios de Internet, este sitio no posee los derechos de propiedad, no se ha realizado un procesamiento editorial humano y no asume ninguna responsabilidad legal relacionada. Si encuentra contenido sospechoso de copyright, le invitamos a enviar un correo electrónico a: notice#oldtoolbag.com (al enviar un correo electrónico, por favor reemplace # con @) para denunciar, y proporcione evidencia relevante. Una vez verificada, este sitio eliminará inmediatamente el contenido sospechoso de infracción.