2011-04-18 6 views
13

Hay alguna manera de definir en el formato XML la definición longKeyLongPress como onClick?Definición de pulsación larga en el diseño XML, como android: onClick hace

es decir este es mi punto de vista

<TextView 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:text="Line 1" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:id="@+id/message" 
android:textSize="15dip" 
android:textStyle="bold" 
android:textColor="@color/colorblue" 
android:shadowDy="1.0" 
android:shadowDx="1.0" 
android:shadowRadius="1.0" 
android:shadowColor="#ffffffff" 
android:paddingLeft="10dip" 
android:paddingRight="10dip" 
android:paddingTop="5dip" 
android:lineSpacingExtra="3dip" 
android:lineSpacingMultiplier="1.1" 
android:singleLine="false" 
android:autoLink="web|email|phone|map|all" 

android:onClick="clickHandler" 
android:clickable="true" 

/> 

quiero algo así antes, pero reaccionando a LongPress evento.

Nota:

  • no quiero añadir oyente de mi código.

  • He intentado con android: longClickable.

Respuesta

5

Mirando la documentación actual, tal parámetro XML no existe actualmente. LongClickable es un parámetro booleano para definir simplemente si una vista responde a clics largos o no.

+1

Acabo de mirar los documentos y llegué a la misma conclusión, es decir, no parece haber un atributo XML para establecer el onLongClickListener y tiene que hacerse con el código. – Squonk

+0

entonces, ¿no hay solución para hacer esto? – vsm

+0

Ninguna de la que tenga conocimiento ... tendrá que hacer lo que no quiere hacer ... agregar el oyente a su código. – Maximus

13

El atributo no está definido, pero puede implementarlo.

  1. Extender TextView y vamos a llamarlo MyTextView.
  2. A continuación, agregue attrs.xml archivo en res/valores/ con los siguientes contenidos:

    <xml version="1.0" encoding="utf-8"?> 
    <resources> 
        <declare-styleable name="MyTextView"> 
         <attr name="onKeyLongPress" format="string"/> 
        </declare-styleable> 
    </resources> 
    
  3. En MyTextView constructor añadir lógica para leer datos de xml:

    public MyTextView(final Context context, final AttributeSet attrs) { 
    super(context, attrs); 
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyTextView); 
    
    for (int i = 0; i < a.getIndexCount(); ++i) 
    { 
        int attr = a.getIndex(i); 
        switch (attr) 
        { 
         case R.styleable.MyTextView_onKeyLongPress: { 
          if (context.isRestricted()) { 
           throw new IllegalStateException("The "+getClass().getCanonicalName()+":onKeyLongPress attribute cannot " 
             + "be used within a restricted context"); 
          } 
    
          final String handlerName = a.getString(attr); 
          if (handlerName != null) { 
           setOnLongClickListener(new OnLongClickListener() { 
            private Method mHandler; 
    
            @Override 
            public boolean onLongClick(final View p_v) { 
             boolean result = false; 
             if (mHandler == null) { 
              try { 
               mHandler = getContext().getClass().getMethod(handlerName, View.class); 
              } catch (NoSuchMethodException e) { 
               int id = getId(); 
               String idText = id == NO_ID ? "" : " with id '" 
                 + getContext().getResources().getResourceEntryName(
                  id) + "'"; 
               throw new IllegalStateException("Could not find a method " + 
                 handlerName + "(View) in the activity " 
                 + getContext().getClass() + " for onKeyLongPress handler" 
                 + " on view " + MyTextView.this.getClass() + idText, e); 
              } 
             } 
    
             try { 
              mHandler.invoke(getContext(), MyTextView.this); 
              result = true; 
             } catch (IllegalAccessException e) { 
              throw new IllegalStateException("Could not execute non " 
                + "public method of the activity", e); 
             } catch (InvocationTargetException e) { 
              throw new IllegalStateException("Could not execute " 
                + "method of the activity", e); 
             } 
             return result; 
            } 
           }); 
          } 
          break; 
         } 
         default: 
          break; 
        } 
    } 
    a.recycle(); 
    
    } 
    
  4. Use un nuevo atributo en su diseño xml:

    <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android" 
        xmlns:custom="http://schemas.android.com/apk/res/res-auto" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:orientation="vertical" 
        > 
    
        <your.package.MyTextView 
         android:id="@+id/theId" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         custom:onKeyLongPress="myDoSomething" 
        /> 
        <!-- Other stuff --> 
    </LinearLayout> 
    

Créditos:

+0

¡Impresionante! Gracias: D – RominaV

Cuestiones relacionadas