2016-07-22 10 views
0

Итак, у меня есть GridLayout, что я хочу показать оба, ImageView & TextView в каждой из его ячеек. Каждый TextView должен быть размещен прямо под номером ImageView в ячейке Grid.Как добавить несколько просмотров в виде одного представления в GridLayout в Android?

Проблема здесь, GridLayout принимает только один просмотр для каждого добавления, в отличие от GridView, где выполняет работу Adapter.

Обратите внимание, что здесь я не могу использовать GridView, так как существует ограничение на ограничение количества строк, поэтому GridView не является для меня вариантом.

Мне было интересно, если бы я мог создать пользовательский вид, который будет содержать два разных вида в пределах &, добавьте его в GridLayout.

Благодарим вас за внимание!

ответ

0

На вашем месте я бы использовал RecyclerView с GridLayoutManager.

Вы можете установить его:

recyclerView.setLayoutManager(new GridLayoutManager(this, 2)); 

, где число указывает на количество строк. Для каждого элемента в RecyclerView вы можете иметь настраиваемый макет (как и во всех адаптерах), который не обязательно должен быть одним Просмотр

1

Да, вы можете создать нестандартный вид.

Создайте файл XML макет в Рез/макета с макетом вы хотите для вида (скорее всего, вертикальная LinearLayout с ImageView и TextView).

Затем создайте класс для своего пользовательского представления, которое раздувает макет.

public class CustomView extends LinearLayout { 
    public CustomView(Context context) { 
     super(context); 

     LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     if(inflater != null){  
      inflater.inflate(R.layout.my_layout, this);   
     } 
    } 
} 

Тогда это можно получить в вашем GridLayout следующим образом:

<GridLayout> 
    <com.yourpackage.CustomView android:id="@+id\id" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 
    </com.yourpackage.CustomView> 
</GridLayout> 
0

Вы правы, вы можете создать свой собственный вид.

Прежде всего, необходимо создать файл макета, который может выглядеть как этот

my_linear_layout.xml

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

    <ImageView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/imageView1" 
     android:src="@android:drawable/sym_def_app_icon" 
     android:layout_gravity="center_horizontal" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="New Text" 
     android:id="@+id/textView1" 
     android:layout_gravity="center_horizontal" /> 
</LinearLayout> 

Затем вы создаете свой собственный класс для этой точки зрения и надуть его

MyView.java

package com.example.stack.test38526476; 

import android.content.Context; 
import android.content.res.TypedArray; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.graphics.drawable.Drawable; 
import android.text.TextPaint; 
import android.util.AttributeSet; 
import android.view.View; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.TextView; 

public class MyView extends LinearLayout { 

    private TextView text; 
    private ImageView image; 

    public MyView(Context context) { 
     super(context); 
     init(); 
    } 

    public MyView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(); 
    } 

    public MyView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     init(); 
    } 

    private void init() { 
     inflate(getContext(), R.layout.my_linear_layout, this); 
     this.text = (TextView)findViewById(R.id.textView1); 
     this.image = (ImageView)findViewById(R.id.imageView1); 
    } 
} 

Наконец, вы можете использовать его в своем GridLayout

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    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" 
    tools:context="com.example.stack.test38526476.MainActivity"> 

    <GridLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true"> 

     <com.example.stack.test38526476.MyView/> 

     <com.example.stack.test38526476.MyView/> 

     <com.example.stack.test38526476.MyView/> 

    </GridLayout> 


</RelativeLayout> 
+0

Почему '' три раза? – Auro