2012-03-20 14 views
32

Tengo un ListView con fastScrollAlwaysVisible y ambos configurados en true. Después de implementar SectionIndexer en mi Adapter y AlphabetIndexer, mi fast scroll thumb desaparecerá mientras me desplazo, luego reapareceré una vez que llegue a la parte superior o inferior de la lista. No tengo ni idea de por qué sucede esto. No lo he experimentado antes.El pulgar de desplazamiento rápido desaparece al desplazarse por AlphabetIndexer

Todo lo que sigue funciona tan lejos como AlphabetIndexer. Mi pregunta es: ¿por qué mi pulgar de desplazamiento rápido desaparece mientras me desplazo y cómo puedo evitar que desaparezca?

Si fast scroll es siempre visible no importa. Siempre que el fast scroll esté visible, el fast scroll thumb no está allí, simplemente se ha ido y ese es mi problema. Además, cuando elimino el AlphabetIndexer el fast scroll thumb funciona como lo pretendo. Todo funciona con éxito en un Activity, pero cuando cargo mi ListView en un Fragment las cosas terminan como explico.

Ésta es mi Adapter para mi ListView:

private class AlbumsAdapter extends SimpleCursorAdapter implements 
     SectionIndexer { 

private AlphabetIndexer mIndexer; 

// I have to override this because I'm using a `LoaderManager` 
@Override 
    public Cursor swapCursor(Cursor cursor) { 

     if (cursor != null) { 
      mIndexer = new MusicAlphabetIndexer(cursor, mAlbumIdx, 
        getResources().getString(R.string.fast_scroll_alphabet)); 
     } 
     return super.swapCursor(cursor); 
    } 

    @Override 
    public Object[] getSections() { 
     return mIndexer.getSections(); 
    } 

    @Override 
    public int getPositionForSection(int section) { 
     return mIndexer.getPositionForSection(section); 
    } 

    @Override 
    public int getSectionForPosition(int position) { 
     return 0; 
    } 
} 

MusicAlphabetIndexer ayuda a clasificar a través de la música correctamente:

class MusicAlphabetIndexer extends AlphabetIndexer { 

public MusicAlphabetIndexer(Cursor cursor, int sortedColumnIndex, 
     CharSequence alphabet) { 
    super(cursor, sortedColumnIndex, alphabet); 
} 

@Override 
protected int compare(String word, String letter) { 
    String wordKey = MediaStore.Audio.keyFor(word); 
    String letterKey = MediaStore.Audio.keyFor(letter); 
    if (wordKey.startsWith(letter)) { 
     return 0; 
    } else { 
     return wordKey.compareTo(letterKey); 
    } 
    } 
} 
+0

que estoy haciendo algo similar AQUÍ http://stackoverflow.com/questions/10224233/alphabetindexer-with-custom-adapter-managed-by-loadermanager – toobsco42

+0

Tomé en su publicación y no vio nada malo. Mi 'SectionIndexer' funciona y no se muestra mientras te desplazas y parece que estás teniendo el problema opuesto, raro. Estoy empezando a pensar que 'Fragments' es el culpable, pero no estoy seguro de cómo hacerlo ahora. Creo que son porque mi 'SectionIndexer' funciona en' ListActivity'. – adneal

+0

Trataré de ver si puedo recrear sus problemas. –

Respuesta

2

¿Tiene tanto fastScrollEnabled y fastScrollAlwaysVisible conjunto de true? No existe el atributo fastScrollAlwaysEnabled de ListView, así que estoy pensando que tal vez solo tiene fastScrollEnabled establecido en verdadero, pero fastScrollAlwaysVisible está configurado en su valor predeterminado, que es false.

+0

Oh, wow. Eso es en realidad un error tipográfico. Me refería a 'fastScrollAlwaysVisible'. También tengo 'fastScrollEnabled' establecido en verdadero. De hecho, actualicé mi OP un poco más. Gracias por comentar, nunca me habría dado cuenta de que cometí un error tipográfico. – adneal

-2

Actividad

import android.app.Activity; 
import android.content.Context; 
import android.database.Cursor; 
import android.os.Bundle; 
import android.widget.AlphabetIndexer; 
import android.widget.ListView; 
import android.widget.SectionIndexer; 
import android.widget.SimpleCursorAdapter; 

public class TestAct extends Activity { 
    /** Called when the activity is first created. */ 
    ListView test_listView; 
    Cursor myCursor; 
    String[] proj; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.list_app_test); 

     TestDummyData cTestDummyData = new TestDummyData(
       getApplicationContext()); 
     cTestDummyData.open(); 
     cTestDummyData.insertRandomNames(); 
     myCursor = cTestDummyData.fetchAllData(); 

     test_listView = (ListView) findViewById(R.id.pager_list_test); 
     test_listView.setFastScrollEnabled(true); 

     test_listView.setAdapter(

     new MyCursorAdapter(getApplicationContext(), 
       android.R.layout.simple_list_item_1, myCursor, 
       new String[] { TestDummyData.KEY_NAME },// names 
       new int[] { android.R.id.text1 }) 

     ); 

     cTestDummyData.close(); 

    } 

    class MyCursorAdapter extends SimpleCursorAdapter implements SectionIndexer { 

     AlphabetIndexer alphaIndexer; 

     // HashMap<String, Integer> alphaIndexer; 
     // String[] sections; 
     public MyCursorAdapter(Context context, int layout, Cursor c, 
       String[] from, int[] to) { 
      super(context, layout, c, from, to); 

      alphaIndexer = new AlphabetIndexer(c, 
        myCursor.getColumnIndex(TestDummyData.KEY_NAME), 
        " ABCDEFGHIJKLMNOPQRSTUVWXYZ"); 
      // ======optional way to get alphaindexer from data 
      // alphaIndexer = new HashMap<String, Integer>(); 
      // int size = items.size(); 
      // 
      // for (int x = 0; x < size; x++) { 
      // String s = items.get(x); 
      // 
      // String ch = s.substring(0, 1); 
      // 
      // ch = ch.toUpperCase(); 
      // 
      // alphaIndexer.put(ch, x); 
      // } 
      // 
      // Set<String> sectionLetters = alphaIndexer.keySet(); 
      // 
      // ArrayList<String> sectionList = new ArrayList<String>(
      // sectionLetters); 
      // 
      // Collections.sort(sectionList); 
      // 
      // sections = new String[sectionList.size()]; 
      // 
      // sectionList.toArray(sections); 

     } 

     @Override 
     public int getPositionForSection(int section) { 
      // TODO Auto-generated method stub 
      return alphaIndexer.getPositionForSection(section); 
     } 

     @Override 
     public int getSectionForPosition(int position) { 
      // TODO Auto-generated method stub 
      return alphaIndexer.getSectionForPosition(position); 
     } 

     @Override 
     public Object[] getSections() { 
      // TODO Auto-generated method stub 
      return alphaIndexer.getSections(); 
     } 

    } 

} 

clase que se utiliza Maniquí de Datos Para la inclusión

import java.util.Random; 

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.util.Log; 

public class TestDummyData { 

    static final String KEY_ID = "_id"; 
    static final String KEY_NAME = "name"; 

    private static final String DB_NAME = "tutorial"; 
    private static final String TABLE_NAME = "names"; 
    private static final int DATABASE_VERSION = 1; 

    private static final String DATABASE_CREATE = "create table " + TABLE_NAME 
      + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME 
      + " varchar not null);"; 

    private Context context; 
    private DatabaseHelper dbHelper; 
    private SQLiteDatabase db; 

    public TestDummyData(Context context) { 
     this.context = context; 
     this.dbHelper = new DatabaseHelper(this.context); 
    } 

    private static class DatabaseHelper extends SQLiteOpenHelper { 
     DatabaseHelper(Context context) { 
      super(context, DB_NAME, null, DATABASE_VERSION); 
     } 

     @Override 
     public void onCreate(SQLiteDatabase db) { 
      db.execSQL(DATABASE_CREATE); 
     } 

     @Override 
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
      Log.v("DBUTIL", "Upgrading database from version " + oldVersion 
        + " to " + newVersion + ", which will destroy all old data"); 
      db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); 
      onCreate(db); 
     } 
    } 

    public void open() { 
     db = dbHelper.getWritableDatabase(); 
    } 

    public void close() { 
     dbHelper.close(); 
    } 

    public void insertRandomNames() { 
     db.execSQL("DELETE FROM " + TABLE_NAME); 
     String s = "ANDROIDDEVELOPER"; 
     Random r = new Random(); 

     ContentValues values = new ContentValues(); 
     for (int i = 0; i < 200; i++) { 
      values.clear(); 
      values.put(KEY_NAME, s.substring(r.nextInt(s.length()))); 
      db.insert(TABLE_NAME, null, values); 
     } 
    } 

    public Cursor fetchAllData() { 
     return db.rawQuery("SELECT * FROM " + TABLE_NAME + " ORDER BY " 
       + KEY_NAME + " ASC", null); 
    } 

} 

la clase anterior es clss de datos ficticios para tarea común ... list_app_test.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 

<ListView 
android:id="@+id/pager_list_test" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content"> 
</ListView> 

</LinearLayout> 

usted acaba de dar test_listView.setFastScrollEnabled (true); gvn ans whter me entiendo de su búsqueda.

+3

Esto no es útil. Sé cómo implementar un 'SectionIndexer'. Lo que no sé es por qué el pulgar de desplazamiento rápido desaparece mientras me desplazo. – adneal

+1

Esta es posiblemente la respuesta menos útil que he encontrado. –

7

Tuve un problema similar con el icono de desplazamiento rápido del pulgar. Estaba investigando el código fuente de Android y encontré un compromiso que introdujo este problema y otro (ArrayIndexOutOfBoundsException). Construí incluso el sistema Android sin este compromiso y funcionó entonces.

presenté el tema en junio: https://code.google.com/p/android/issues/detail?id=33293
cuando estoy leyendo se sabe que veo yo podría describir mejor el asunto :)

Este es el commit que está haciendo problemas: https://github.com/android/platform_frameworks_base/commit/32c3a6929af9d63de3bf45a61be6e1a4bde136d3

Desafortunadamente No he encontrado ninguna solución, excepto revertir el compromiso, y lo dejé.
Espero que alguien encuentre cómo solucionarlo.

+0

Sí, sospechaba que era un error de framework. También he visto otras aplicaciones en Play Store experimentar lo mismo. Me alegro de que hayas publicado esto. – adneal

0

Puede comprobar este código:

int currentapiVersion = android.os.Build.VERSION.SDK_INT; 
if (currentapiVersion <= android.os.Build.VERSION_CODES.FROYO){ 
    // Do something for froyo and above versions 
    list.setFastScrollEnabled(true); 


} else if(currentapiVersion > android.os.Build.VERSION_CODES.HONEYCOMB){ 
    // do something for phones running an SDK before froyo 
    list.setFastScrollEnabled(true); 
    list.setFastScrollAlwaysVisible(true); 
} 
+0

Guau, [que] (https://stackoverflow.com/a/30370154/1677912) [código] (http://stackoverflow.com/a/29958384/1677912) [obtiene] (http://stackoverflow.com/a/34332188/1677912) [alrededor] (http://stackoverflow.com/a/3940823/1677912). Sugiérale que proporcione la atribución del código que ha encontrado. (La estructura básica es de documentos, ¿verdad?) – Mogsdad

+0

[setFastScrollAlwaysVisible] (http://developer.android.com/intl/es/reference/android/widget/AbsListView.html#setFastScrollAlwaysVisible (boolean)) -> Establece si el desplazamiento rápido debe o no siempre se mostrará en lugar de las barras de desplazamiento estándar. – Cabezas

Cuestiones relacionadas