Android
RubMAIN
public class MainActivity extends AppCompatActivity implements ListaFragment.OnLibroSeleccionadoListener{ public static final int INSERT_CODE = 0; public static final int EDIT_CODE = 1; public static final int RESUMEN_CODE=2; public static final String TITULO = "titulo"; public static final String AUTOR = "autor"; public static final String RESUMEN = "resumen"; public static final String GENERO = "genero"; public static final String POSICION = "posicion"; ArrayList<Libro> modelo; ArrayAdapter<Libro> adapter; ListView lv; int pos; // Posición del elemento actual de la lista Libro l; //atributos para los fragments ListaFragment lf; NoSeleccionadoFragment nsf; ResumenFragment rf; FormFragment ff = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_main); lf = new ListaFragment(); this.l = new Libro("","",Libro.Genero.NARRATIVA,""); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); //Versión de Support //FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.add(R.id.contenedor_lista, lf); if(grande()){ //Se ha cargado el layout con dos contenedores. Habrá que instanciar y cargar el segundo fragment nsf = new NoSeleccionadoFragment(); transaction.replace(R.id.contenedor_resumen, nsf); } transaction.commit(); }//onCreate public boolean grande(){ return (findViewById(R.id.contenedor_lista)!=null); }
MI ADAPTER
public class MiAdapter extends ArrayAdapter<Libro>{ static class ViewHolder{ protected TextView tv_titulo; protected TextView tv_autor; protected LinearLayout ll; } private Activity ctx = null; private ArrayList<Libro> modelo; public MiAdapter(Activity ctx, ArrayList<Libro> modelo){ super(ctx, R.layout.layout_row, modelo); this.ctx = ctx; this.modelo = modelo; } public View getView(int position, View convertView, ViewGroup parent){ View row = convertView; //reciclada if(row == null){ /* el listView aún no está lleno; es decir, faltan filas por instanciar. En este caso tenemos que instanciar la fila completa: inflar el layout */ row = ctx.getLayoutInflater().inflate(R.layout.layout_row, null); /*Al inflar una fila nueva, el ViewHolder guarda los ids y no tendremos que hacer findviewbyid en el futuro*/ ViewHolder vh = new ViewHolder(); vh.tv_titulo = (TextView)row.findViewById(R.id.row_titulo); vh.tv_autor = (TextView)row.findViewById(R.id.row_autor); vh.ll = (LinearLayout) row.findViewById(R.id.row_layout); row.setTag(vh); } //buscamos el libro en el modelo (ArrayList) por su posición ViewHolder vh = (ViewHolder)row.getTag(); Libro l = modelo.get(position); vh.tv_titulo.setText(l.titulo); vh.tv_autor.setText(l.autor); /*Libro l = modelo.get(position); tv_titulo.setText(l.getTitulo()); tv_autor.setText(l.getAutor());*/ if (l.genero.equals(Libro.Genero.NARRATIVA)) { vh.ll.setBackgroundColor(Color.CYAN); } else if (l.genero.equals(Libro.Genero.TEATRO)) { vh.ll.setBackgroundColor(Color.YELLOW); } else if (l.genero.equals(Libro.Genero.POESIA)) { vh.ll.setBackgroundColor(Color.GREEN); } return row; }
NO SELECCIONADO FRAGMENT
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View result=inflater.inflate(R.layout.fragment_no_seleccionado,container,false); return result; } @Override public void onAttach(Context activity){ super.onAttach(activity); //TODO De momento no hacemos nada } public void onDetach(){ super.onDetach(); } public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); }
LISTA FRAGMENT
public class ListaFragment extends Fragment { /*Creamos interfaces que obligue a la actividad a implementar ciertos métodos en respuesta a eventos El fragment solo se enganchará a esa actividad (onAttach) si implementa las interfaces adecuadas */ //INTERFACES public interface OnLibroSeleccionadoListener{ public void onLibroSeleccionado(Libro l); } public interface OnInsertarLibroListener{ public long onInsertar(); } //ATRIBUTOS protected ListView lv; protected MiAdapter aa; protected ArrayList<Libro> modelo; private OnLibroSeleccionadoListener listener_seleccion = null; //Al principio no escucha //private OnInsertarListener listener_insercion = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ //Generar los datos modelo = new ArrayList<Libro>(); modelo.add(new Libro("El Quijote", "Cervantes", Libro.Genero.TEATRO)); modelo.add(new Libro("Libroprueba", "Sakurai", Libro.Genero.POESIA)); modelo.add(new Libro("Librito", "Hodor", Libro.Genero.NARRATIVA)); modelo.add(new Libro("Librete", "Crudo", Libro.Genero.NARRATIVA)); modelo.add(new Libro("El Vacío", "Nomura", Libro.Genero.TEATRO)); //inflar el layout del fragment con referencia al contenedor de alguna actividad View result = inflater.inflate(R.layout.fragment_lista, container, false); //rellenar el listView utilizando el adapter aa = new MiAdapter(getActivity(), modelo); lv = (ListView) result.findViewById(R.id.lista); lv.setAdapter(aa); //Colocar el listener de clicks lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(listener_seleccion!=null){ Libro l= aa.getItem(position); listener_seleccion.onLibroSeleccionado(l); } } }); Button b = (Button) result.findViewById(R.id.button_lista); b.setOnClickListener( new View.OnClickListener(){ public void onClick(View v){ ((MainActivity)getActivity()).onInsertar(); } } ); return result; }
LAYOUT_MAIN (large)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:id="@+id/contenedor_lista" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"/> <FrameLayout android:id="@+id/contenedor_resumen" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"/> </LinearLayout>
LAYOUT_ROW
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/row_layout" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16px"> <TextView android:id="@+id/row_titulo" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:id="@+id/row_autor" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
FRAGMENT_LISTA
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="com.barajas.ruben.bibliotecatablet.MainActivity" android:weightSum="1"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tv_titulo" /> <ListView android:id="@+id/lista" android:layout_width="match_parent" android:layout_height="298dp" android:layout_weight="0.86"></ListView> <Button android:id="@+id/button_lista" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/agregar" android:onClick="onPulsame"/> </LinearLayout>
FRAGMENT NO SELECCIONADO
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_height="wrap_content" android:layout_width="match_parent" android:text="@string/mensaje_no_seleccionado" android:gravity="center" style="@style/TextAppearance.AppCompat.Headline"/> </LinearLayout>