Android - GridView высота до максимальной высоты - PullRequest
0 голосов
/ 23 марта 2012

У меня есть GridView внутри scrollview, и в GridView загружено 4 изображения (через ImageAdapter). Моя проблема в том, что я могу показать 3 изображения, а 4-е - нет. После дальнейшего изучения я обнаружил, что высота вида сетки - это только высота строки, поэтому, если я установлю высоту вида сетки в xml на 700dp, то она отобразится.

Вот скриншот:

enter image description here

Как вы можете видеть, я установил фон GridView на HotPink, чтобы проиллюстрировать, где находится GridView.

Вот XML для main_menu:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/llLayoutContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >    

    <!-- <LinearLayout android:id="@+id/llMiddle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal"> -->

        <LinearLayout
            android:id="@+id/llLeft"
            android:layout_width="400dp"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:background="@drawable/layout_left"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"> 
            <ScrollView 
                android:id="@+id/svMenu"
                android:layout_width="400dp"
                android:layout_height="match_parent"
                >
            </ScrollView>           
        </LinearLayout>

        <LinearLayout
            android:id="@+id/llRight"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical"
            android:background="@drawable/layout_right"
            android:padding="0dp"> 
        </LinearLayout>
    <!-- </LinearLayout> -->
</LinearLayout>

LinearLayout "llLeft" - это макет, в который загружаются элементы меню (внутри ScrollView). layout_left - это только фигура, которая рисует темный контур вокруг зеленоватого фона.

Вот main_menu_header.xml, который содержит GridView:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingTop="5dp">

    <TextView
             android:id="@+id/tvDashboardHeader"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:text="Dashboard Main Menu"
             android:textSize="20dp"
             style="@style/TextShadow"
             android:paddingTop="5dp"
             android:gravity="left"
             android:background="@drawable/menu_item_bg"        
            />
    <GridView 
        android:id="@+id/gvMenuItems"
        android:layout_width="400dp"
        android:layout_height="match_parent"
        android:columnWidth="110dp"
        android:numColumns="auto_fit"    
        android:verticalSpacing="10dp"    
        android:horizontalSpacing="10dp"    
        android:stretchMode="columnWidth"
        android:background="@color/HotPink"
        android:gravity="center" >
    </GridView>

</LinearLayout>

А вот как я заполняю GridView:

        ScrollView sv = (ScrollView)findViewById(R.id.svMenu);
        LayoutInflater liInflater = getLayoutInflater();
        ViewGroup vg = (ViewGroup)liInflater.inflate(R.layout.main_menu_header, sv, false);
        sv.addView(vg);

        //Setup the Main Menu items on the left side.
        GridView gvMenuItems = (GridView) findViewById(R.id.gvMenuItems);    
        gvMenuItems.setAdapter(new ImageAdapter(this));

Класс ImageAdapter:

Класс ImageAdapter:

public class ImageAdapter extends BaseAdapter {
    private Context mContext;    

    public ImageAdapter(Context c) {
        mContext = c;    
    }    

    public int getCount() {        
        return mThumbIds.length;    
    }    

    public Object getItem(int position) {        
        return null;    
    }    

    public long getItemId(int position) {        
        return 0;    
    }    

    // create a new ImageView for each item referenced by the Adapter    
    public View getView(int position, View convertView, ViewGroup parent) {        

        ImageView imageView;

        if (convertView == null) {
            // if it's not recycled, initialize some attributes            
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(parent.getLayoutParams().width, 125)); //new GridView.LayoutParams(400, 125));             
            //imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            imageView.setMaxHeight(50);
            imageView.setMaxWidth(50);
            //imageView.setPadding(30, 0, 0, 0);
            //imageView.setPadding(40, 30, 20, 30);

            } else {            
                imageView = (ImageView) convertView;        
            }        

        imageView.setImageResource(mThumbIds[position]);

        return imageView;
    }    

    // references to our images    
    private Integer[] mThumbIds = {
            R.drawable.home,
            R.drawable.open_folder, 
            R.drawable.paper_pen,
            R.drawable.person
    };
}

Я думал, что свойство gridview android: layout_height = "match_parent" будет работать, но это не так. Любые идеи относительно того, как я могу заставить GridView занимать всю левую сторону, внутри прокрутки?

1 Ответ

1 голос
/ 23 марта 2012

Мое лучшее предположение, что scrollview доставляет вам проблемы.

Зачем вам scrollview для?

Grid View будет обрабатывать прокрутку.Это отчасти избыточно. Поэтому, пожалуйста, удалите его и добавьте раздутый вид непосредственно к llLeft напрямую.Это решит проблему.


На самом деле, было бы более элегантно просто использовать xml для решения проблемы пользовательского интерфейса.Используйте тег <include> в вашем main_menu.xml.Вот как

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/llLayoutContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >    

<!-- <LinearLayout android:id="@+id/llMiddle"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="horizontal"> -->

    <LinearLayout
        android:id="@+id/llLeft"
        android:layout_width="400dp"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@drawable/layout_left"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"> 
        <include
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         layout="@layout/main_menu_header" />           
    </LinearLayout>

    <LinearLayout
        android:id="@+id/llRight"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:background="@drawable/layout_right"
        android:padding="0dp"> 
    </LinearLayout>
<!-- </LinearLayout> -->

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...