2012-03-09 18 views
8

Necesito mostrar una lista de elementos de texto en la pantalla y hacer que se puedan hacer clic. Por lo tanto, sería algo así como una lista de enlaces en una aplicación web.Aplicación de Android: cómo mostrar una lista de elementos y hacerlos clics

¿Cómo puedo hacer eso en una pantalla de actividad de Android?

Sería un número aleatorio de elementos que tengo que extraer de un db y mostrar todos como enlaces.

¿Alguna idea de cómo se puede hacer eso?

Respuesta

3

Debe usar un ListView. Es muy simple, solo crea un ListActivity, coloca tus artículos dentro de un Adapter y luego configúralo como el Adapter de tu ListActivity.

Puede leer más sobre listviews here

1

También hay un nuevo paradigma denominado ListFragment.

He usado ListViews antes, pero prefiero el enfoque de fragmentos ahora - es muy simple y bastante flexible especialmente en tabletas ya que la interacción con otra área en la pantalla cuando se selecciona un elemento es bastante flexible y solo requiere muy poco código.

Sólo un ejemplo:

public class Select_FoodCategories_Fragment extends android.app.ListFragment { 
    private static final boolean DEBUG = true; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    if (DEBUG) 
     Log.i(this.getClass().getSimpleName(), " ->" 
      + Thread.currentThread().getStackTrace()[2].getMethodName()); 
    super.onCreate(savedInstanceState); 

    } 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState); 
    if (DEBUG) 
     Log.i(this.getClass().getSimpleName(), " ->" 
      + Thread.currentThread().getStackTrace()[2].getMethodName()); 
    HoldingActivity a = (HoldingActivity) getActivity(); 
    //accessing a variable of the activity is easy 
    a.visibleListViewInFragment = getListView(); 

    List<XYZ> listTodisplay = a.getListToDisplay(); 

    MyAdapter adapter = new MyAdapter(
     getActivity(), 0, listTodisplay); 
    setListAdapter(adapter); 

    } 

    @Override 
    public void onListItemClick(ListView l, View v, int position, long id) { 
    if (DEBUG) 
     Log.i(this.getClass().getSimpleName(), " ->" 
      + Thread.currentThread().getStackTrace()[2].getMethodName()); 
     XYZ item = (XYZ) getListAdapter() 
     .getItem(position); 

    } 

} 

Más información aquí: http://developer.android.com/reference/android/app/ListFragment.html

Por cierto, creo que es realmente vale la pena para familiarizarse con el nuevo concepto de fragmentos - sólo hace vivir mucho más fácil - esp en tabletas!

ps me dejó las instrucciones de depuración en el objetivo - ya que ayuda a entender Alto todo el concepto mucho más rápido en mi experiencia

8

Sí puede hacerlo. Cree una clase DataExchange para recuperarla de Db .. Almacene las cadenas en una matriz.

Cree un ArrayAdapter para visualizar la matriz de cadenas que obtuvo de la base de datos.

para el Ejemplo

public class AndroidListViewActivity extends ListActivity { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    // storing string resources into Array 
    String[] numbers = {"one","two","three","four"} 
    // here you store the array of string you got from the database 

    // Binding Array to ListAdapter 
    this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label,  numbers)); 
    // refer the ArrayAdapter Document in developer.android.com 
    ListView lv = getListView(); 

    // listening to single list item on click 
    lv.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View view, 
      int position, long id) { 

      // selected item 
      String num = ((TextView) view).getText().toString(); 

      // Launching new Activity on selecting single List Item 
      Intent i = new Intent(getApplicationContext(), SingleListItem.class); 
      // sending data to new activity 
      i.putExtra("number", num); 
      startActivity(i); 

     } 
    }); 
} 
} 

El secondActivity para mostrar el elemento especial que haya hecho clic debería ser

public class SingleListItem extends Activity{ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    this.setContentView(R.layout.single_list_item_view); 

    TextView txtProduct = (TextView) findViewById(R.id.product_label); 

    Intent i = getIntent(); 
    // getting attached intent data 
    String product = i.getStringExtra("number"); 
    // displaying selected product name 
    txtProduct.setText(product); 

} 
} 

usted tiene que crear varios archivos de diseño en consecuencia .. Espero que esto ayude :)

Cuestiones relacionadas