2012-06-08 16 views
5

Tengo una vista web que muestra un archivo html. Cuando el usuario se desplaza al final de este archivo en la vista web, quiero que aparezca un botón que estaba oculto previamente, que el usuario puede presionar para realizar alguna actividadAndroid: Hacer que un botón sea visible una vez que la vista web se haya realizado al desplazarse

Hice algo similar en iOS, donde acabo de configurar delegue en ViewController y simplemente configure el botón como visible. ¿Cómo hago algo similar en Android? Noté que no hay un método de devolución de llamada como en iOS.

Editar: En este momento, tengo una actividad con 2 objetos: una vista web que contiene mi texto, y un botón que actualmente es invisible. Quiero que mi actividad para recibir un mensaje cuando el texto se desplaza WebView a la parte inferior, y hacer visible el botón

Respuesta

0

probar esto:

@Override 
protected void onScrollChanged(int l, int t, int oldl, int oldt) { 
     View view = (View) getChildAt(getChildCount()-1); 
     int diff = (view.getBottom()-(getHeight()+getScrollY()));// Calculate the scrolldiff 
     if(diff == 0){ // if diff is zero, then the bottom has been reached 
      Log.d(ScrollTest.LOG_TAG, "MyScrollView: Bottom has been reached"); 
      yourButton.setVisible(true); 
     } 
     super.onScrollChanged(l, t, oldl, oldt); 
} 

Para implementar esto, se extienden ScrollView y luego reemplazar el método onScrollChanged (heredado desde la vista).

+0

Sin embargo, la vista web no hace referencia al botón. – Daniel

2

Tuve que hacer esto yo mismo, para mostrar el botón "Acepto" una vez que el usuario se haya desplazado al final de un EULA. Abogados, ¿eh?

De hecho, cuando anula WebView (en lugar de ScrollView como en la respuesta de @JackTurky) puede llamar a getContentHeight() para obtener el alto del contenido, en vez de getBottom() que devuelve el fondo visible y es Inútil.

Esta es mi solución integral. Por lo que puedo ver, esto es todo lo de API Nivel 1, por lo que debería funcionar en cualquier lugar.

public class EulaWebView extends WebView { 
    public EulaWebView(Context context) 
    { 
     this(context, null); 
    } 

    public EulaWebView(Context context, AttributeSet attrs) 
    { 
     this(context, attrs, 0); 
    } 

    public EulaWebView(Context context, AttributeSet attrs, int defStyle) 
    { 
     super(context, attrs, defStyle); 
    } 

    public OnBottomReachedListener mOnBottomReachedListener = null; 
    private int mMinDistance = 0; 

    /** 
    * Set the listener which will be called when the WebView is scrolled to within some 
    * margin of the bottom. 
    * @param bottomReachedListener 
    * @param allowedDifference 
    */ 
    public void setOnBottomReachedListener(OnBottomReachedListener bottomReachedListener, int allowedDifference) { 
     mOnBottomReachedListener = bottomReachedListener; 
     mMinDistance = allowedDifference; 
    } 

    /** 
    * Implement this interface if you want to be notified when the WebView has scrolled to the bottom. 
    */ 
    public interface OnBottomReachedListener { 
     void onBottomReached(View v); 
    } 

    @Override 
    protected void onScrollChanged(int left, int top, int oldLeft, int oldTop) { 
     if (mOnBottomReachedListener != null) { 
      if ((getContentHeight() - (top + getHeight())) <= mMinDistance) 
       mOnBottomReachedListener.onBottomReached(this); 
     } 
     super.onScrollChanged(left, top, oldLeft, oldTop); 
    } 

} 

Lo utilizo para mostrar un botón de "Aceptar" una vez que el usuario ha desplazado hasta la parte inferior de la vista Web, donde yo lo llamo así (en una clase que "implementa OnBottomReachedListener":

EulaWebView mEulaContent; 
Button mEulaAgreed; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.eula); 
    mEulaContent = (EulaWebView) findViewById(R.id.eula_content); 
    StaticHelpers.loadWebView(this, mEulaContent, R.raw.stylesheet, StaticHelpers.readRawTextFile(this, R.raw.eula), null); 
    mEulaContent.setVerticalScrollBarEnabled(true); 
    mEulaContent.setOnBottomReachedListener(this, 50); 

    mEulaAgreed = (Button) findViewById(R.id.eula_agreed); 
    mEulaAgreed.setOnClickListener(this); 
    mEulaAgreed.setVisibility(View.GONE); 
} 

@Override 
public void onBottomReached(View v) { 
    mEulaAgreed.setVisibility(View.VISIBLE); 
} 

Así que cuando se llega a la parte inferior (o en este caso, cuando se hacen dentro de los 50 píxeles de la misma) el botón "Acepto" aparece el botón.

+0

Hola, ¿podría decirme dónde 'StaticHelpers' ha sido declarado? –

+0

StaticHelpers es una clase interna con algunos métodos de uso general, en este caso para cargar una vista web y para leer un archivo de texto del sistema de archivos, nada particularmente sorprendente allí. – karora

-1

soluciones anteriores no funcionó para mí totalmente para el problema similar (botón ocultar mientras se está desplazando webView, mostrar después de que el desplazamiento ha terminado). La razón por la que wante D ocultarlo mientras se desplaza es porque el botón que quiero ocultar es para saltar al final de la vista web, y cuando solo funcionó para mí cuando webview es estático, pero no saltó a la parte inferior mientras la vista todavía se está desplazando. Así que hice lo siguiente:

añade una devolución de llamada onScrollChanged a anulado web View, como sugirió cercana:

private OnScrollChangedCallback mOnScrollChangedCallback; 

public OnScrollChangedCallback getOnScrollChangedCallback() { 
    return mOnScrollChangedCallback; 
} 

public void setOnScrollChangedCallback(
     final OnScrollChangedCallback onScrollChangedCallback) { 
    mOnScrollChangedCallback = onScrollChangedCallback; 
} 

@Override 
protected void onScrollChanged(final int l, final int t, final int oldl, 
     final int oldt) { 
    super.onScrollChanged(l, t, oldl, oldt); 
    if (mOnScrollChangedCallback != null){ 
     mOnScrollChangedCallback.onScrollChanged(l, t); 
    } 
} 

/** 
* Implement in the activity/fragment/view that you want to listen to the 
* webview 
*/ 
public static interface OnScrollChangedCallback { 
    public void onScrollChanged(int l, int t); 
} 

y en mi clase de actividad que implementa OnScrollChangedCallback

Actualizado:

Timer timer2showJumpButton; 
private long lastScrollEventTimestamp; 
public final static int HIDING_JUMP_BUTTON_ON_SCROLL_DELAY = 500; 

    public void onScrollChanged(int l, int t) { 

    // showing button when scrolling starts 
    if (btnJumpToBottom != null) { 
     btnJumpToBottom.setVisibility(View.VISIBLE); 
    } 

    if (btnJumpToTop!= null) { 
     btnJumpToTop.setVisibility(View.VISIBLE); 
    } 


    if (timer2showJumpButton == null) { 

     final Runnable r2 = new Runnable() { 

      @Override 
      public void run() { 
       if (btnJumpToBottom != null) { 
        btnJumpToBottom.setVisibility(View.GONE); 
       } 
       if (btnJumpToTop!= null) { 
        btnJumpToTop.setVisibility(View.GONE); 
       } 

      } 
     }; 

     TimerTask timerTask = new TimerTask() { 
      @Override 
      public void run() { 
       if (btnJumpToTop.getVisibility() == View.VISIBLE || btnJumpToBottom.getVisibility() == View.VISIBLE){ 
        long currentTimestamp = System.currentTimeMillis(); 

        if (currentTimestamp - lastScrollEventTimestamp > HIDING_JUMP_BUTTON_ON_SCROLL_DELAY1){       
         webView.postDelayed(r2, HIDING_JUMP_BUTTON_ON_SCROLL_DELAY); 
        }else{ 
         //too soon 
        } 
       } 
      } 
     }; 

     try { 
      timer2showJumpButton = new Timer(); 
      timer2showJumpButton.schedule(timerTask, 500, 500); 
     } catch (IllegalStateException e) { 
      logger.warn(TAG + "/onScrollChanged/" + e.getMessage()); 

     } 
    } 

    // adding runnable which will hide button back 
    long currentTimestamp = System.currentTimeMillis(); 

    lastScrollEventTimestamp = currentTimestamp; 
} 
+0

Descubrió que "web.pageDown (true);" funciona durante el desplazamiento, pero "web.scrollTo (0, scrollTo);" es ignorado – shtolik

+0

Cuando se desplaza la página, obtendrá cientos de devoluciones de llamada onScrollChanged, y eso asignará una gran cantidad de objetos Timer :) Una forma sería tener un temporizador/hilo, que se ejecutará con un intervalo fijo (~ 500ms). Luego, registrará la última marca de tiempo de desplazamiento en onScrollChanged, y deshabilitará/habilitará los botones en el temporizador según la última marca de tiempo de desplazamiento. – noxo

+0

Respuesta actualizada en consecuencia – shtolik

0

Cargando/Botón visible solo cuando se accede a la vista web/se desplaza hasta la parte inferior.

Crear clase de JavaScript:

public class JavaScriptInterface { 

    @android.webkit.JavascriptInterface 
    public void didScrollToBottom() { 
    Log.d(TAG, "Scroll to Bottom"); 
    myHandler.post(new Runnable() { 
     @Override 
     public void run() { 
     btnAccept.setVisibility(View.VISIBLE); 

      } 
     }); 
     } 
    } 

En onCreate():

final JavaScriptInterface jsInterface = new JavaScriptInterface(); 
myWebView.addJavascriptInterface(jsInterface, "AndroidFunction"); 
0

[que no puedo comentar sobre una respuesta, así que dejar mi comentario aquí una nueva respuesta]

La respuesta de karora (la primera) funciona muy bien, excepto que en el

protected void onScrollChanged(int left, int top, int oldLeft, int oldTop) 
método

, llamando

getContentHeight() 

era muy impreciso para mí. Informó de un valor demasiado pequeño, por lo que se llamó a mi oyente cuando el usuario solo se había desplazado tal vez un tercio del camino de WebView. Usé

computeVerticalScrollRange() 

cambio, y eso es perfecto. Gracias a this post por esa sugerencia útil.

Cuestiones relacionadas