una tamaño imagen formulario fila eliminar contenido como columna cambiar autosizecolumnsmode alto ajustar android android-layout android-gridview

android - imagen - cambiar tamaño columna gridview c#



Gridview con dos columnas e imágenes con cambio de tamaño automático (2)

Estoy tratando de hacer una vista de cuadrícula con dos columnas. Me refiero a dos fotos por fila, una al lado de la otra, al igual que esta imagen.

Pero mis imágenes tienen espacios entre ellas, debido a que no tienen el mismo tamaño. Esto es lo que obtendré.

como puede ver, la primera imagen oculta la leyenda que muestra el nombre del contacto y el número de teléfono. y las otras imágenes no se estiran correctamente.

Aquí está mi archivo GridView xml. Como puede ver, el columnWidth está establecido en 200dp . Me gustaría que fuera automático , por lo que las imágenes cambiarán de tamaño automáticamente para cada tamaño de pantalla.

<?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gridViewContacts" android:layout_width="fill_parent" android:layout_height="fill_parent" android:numColumns="2" android:columnWidth="200dp" android:stretchMode="columnWidth" android:gravity="center" />

y aquí está el archivo xml del elemento, que representa cada elemento en sí.

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/imageViewContactIcon" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="fitXY" /> <LinearLayout android:id="@+id/linearlayoutContactName" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingLeft="5dp" android:paddingTop="5dp" android:paddingBottom="5dp" android:background="#99000000" android:layout_alignBottom="@+id/imageViewContactIcon"> <TextView android:id="@+id/textViewContactName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFFFFF" android:textStyle="bold" android:textSize="15sp" android:text="Lorem Ipsum" /> <TextView android:id="@+id/textViewContactNumber" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFFFFF" android:layout_marginLeft="5dp" android:focusable="true" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:textSize="10sp" android:text="123456789" /> </LinearLayout> </RelativeLayout>

Entonces, lo que quiero es mostrar dos imágenes por fila, y las imágenes cambian de tamaño automáticamente, sin importar el tamaño de la pantalla. ¿Qué estoy haciendo mal en mi diseño?

Gracias.


Aquí hay un método relativamente fácil de hacer esto. Lanza un GridView en tu diseño, configura el modo de estiramiento para estirar el ancho de las columnas, establece el espaciado en 0 (o lo que quieras), y establece el número de columnas en 2:

res / layout / main.xml

<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <GridView android:id="@+id/gridview" android:layout_width="match_parent" android:layout_height="match_parent" android:verticalSpacing="0dp" android:horizontalSpacing="0dp" android:stretchMode="columnWidth" android:numColumns="2"/> </FrameLayout>

Cree un ImageView personalizado que mantenga su relación de aspecto:

src / com / example / graphicstest / SquareImageView.java

public class SquareImageView extends ImageView { public SquareImageView(Context context) { super(context); } public SquareImageView(Context context, AttributeSet attrs) { super(context, attrs); } public SquareImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width } }

Haz un diseño para un elemento de cuadrícula usando este SquareImageView y configura scaleType en centerCrop:

res / layout / grid_item.xml

<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.graphicstest.SquareImageView android:id="@+id/picture" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop"/> <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingLeft="10dp" android:paddingRight="10dp" android:paddingTop="15dp" android:paddingBottom="15dp" android:layout_gravity="bottom" android:textColor="@android:color/white" android:background="#55000000"/> </FrameLayout>

Ahora haz algún tipo de adaptador para tu GridView :

src / com / example / graphicstest / MyAdapter.java

private final class MyAdapter extends BaseAdapter { private final List<Item> mItems = new ArrayList<Item>(); private final LayoutInflater mInflater; public MyAdapter(Context context) { mInflater = LayoutInflater.from(context); mItems.add(new Item("Red", R.drawable.red)); mItems.add(new Item("Magenta", R.drawable.magenta)); mItems.add(new Item("Dark Gray", R.drawable.dark_gray)); mItems.add(new Item("Gray", R.drawable.gray)); mItems.add(new Item("Green", R.drawable.green)); mItems.add(new Item("Cyan", R.drawable.cyan)); } @Override public int getCount() { return mItems.size(); } @Override public Item getItem(int i) { return mItems.get(i); } @Override public long getItemId(int i) { return mItems.get(i).drawableId; } @Override public View getView(int i, View view, ViewGroup viewGroup) { View v = view; ImageView picture; TextView name; if (v == null) { v = mInflater.inflate(R.layout.grid_item, viewGroup, false); v.setTag(R.id.picture, v.findViewById(R.id.picture)); v.setTag(R.id.text, v.findViewById(R.id.text)); } picture = (ImageView) v.getTag(R.id.picture); name = (TextView) v.getTag(R.id.text); Item item = getItem(i); picture.setImageResource(item.drawableId); name.setText(item.name); return v; } private static class Item { public final String name; public final int drawableId; Item(String name, int drawableId) { this.name = name; this.drawableId = drawableId; } } }

Configure ese adaptador a su GridView :

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GridView gridView = (GridView)findViewById(R.id.gridview); gridView.setAdapter(new MyAdapter(this)); }

Y disfruta los resultados:


Otro enfoque simple con elementos incorporados modernos como PercentRelativeLayout ahora está disponible para los nuevos usuarios que tengan este problema. Gracias al equipo de Android por lanzar este artículo.

<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:clickable="true" app:layout_widthPercent="50%"> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/picture" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" /> <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:background="#55000000" android:paddingBottom="15dp" android:paddingLeft="10dp" android:paddingRight="10dp" android:paddingTop="15dp" android:textColor="@android:color/white" /> </FrameLayout>

y para un mejor rendimiento puedes usar algunas cosas como el cargador de imágenes picasso que te ayuda a llenar el ancho completo de cada imagen de los padres. por ejemplo, en su adaptador debe usar esto:

int width= context.getResources().getDisplayMetrics().widthPixels; com.squareup.picasso.Picasso .with(context) .load("some url") .centerCrop().resize(width/2,width/2) .error(R.drawable.placeholder) .placeholder(R.drawable.placeholder) .into(item.drawableId);

ahora ya no necesitas clases CustomImageView.

PD: recomiendo usar ImageView en lugar de Type Int en la clase Item.

espero que esto ayude..