2013-09-23 3 views
0

У меня возникли проблемы с получением информации о содержании контента GridView программно, так как я размещаю его внутри ScrollView, мне просто нужно увеличить динамическую высоту GridView, получив его высоту содержимого в PIXELS. Вот что я сделал:Как рассчитать высоту содержимого GridView в пикселях?

@Override 
public void onWindowFocusChanged(boolean hasFocus) 
{ 
    // TODO Auto-generated method stub 
    super.onWindowFocusChanged(hasFocus); 
    System.out.println("...111Height..."+gridView.getMeasuredWidth()); 
} 

, но я хочу, чтобы получить значение внутри OnCreate, так что я могу кормить его layoutParams.height в:

GridView gridView = (GridView) findViewById(R.id.gridview_module); 
    ViewGroup.LayoutParams layoutParams = gridView.getLayoutParams(); 
    layoutParams.height = convertDpToPixels(iDontKnowWhatToPutHere, this); 
    gridView.setLayoutParams(layoutParams); 

и метод для преобразования из пикселей дп:

public static int convertDpToPixels(float dp, Context context) { 
    Resources resources = context.getResources(); 
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, 
      resources.getDisplayMetrics()); 
} 

EDIT:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/mainLayout" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
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=".SecondActivity" > 

<ScrollView 
    android:id="@+id/scrollview" 
    android:layout_width="match_parent" 
    android:layout_height="0" 
    android:layout_weight="1" 
    android:fillViewport="true" 
    android:scrollbars="none" > 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical" > 

     <TextView 
      android:id="@+id/tv" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="@string/hello_world" /> 

     <com.example.ExpandableHeightGridView 
      android:id="@+id/gridview_module" 
      android:layout_width="match_parent" 
      android:layout_height="0dp" 
      android:layout_below="@id/tv" 
      android:layout_weight="1" 
      android:gravity="center" 
      android:horizontalSpacing="20dp" 
      android:numColumns="3" 
      android:stretchMode="columnWidth" 
      android:verticalSpacing="10dp" /> 

     <Button 
      android:id="@+id/dial_phone" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_below="@id/gridview_module" 
      android:onClick="dialPhone" 
      android:text="Dial Phone" /> 
    </LinearLayout> 
</ScrollView> 

ответ

0

Для достижения этой цели необходимо создать CustomGridview как этот

public class CustomGridView extends GridView { 

    private int old_count; 
    private android.view.ViewGroup.LayoutParams params; 
    private boolean isExpandFully = false; 
    private int verticleSpacing = 4; 
    private int noOfCollumns = 1; 

    public int getNumColumns() { 
     return noOfCollumns; 
    } 

    public void setNoOfCollumns(int noOfCollumns) { 
     this.noOfCollumns = noOfCollumns; 
    } 

    public int getVerticleSpacing() { 
     return verticleSpacing; 
    } 

    public void setVerticleSpacing(int verticleSpacing) { 
     this.verticleSpacing = verticleSpacing; 
    } 

    public void setExpandFully(boolean isExpandFully) { 
     this.isExpandFully = isExpandFully; 
    } 

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

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

    public CustomGridView(Context context) { 
     super(context); 
     init(null); 
    } 

    private void init(AttributeSet attrs) { 
     if (attrs != null) { 
      String namespace = "http://schemas.android.com/apk/res/android"; 
      noOfCollumns = attrs.getAttributeIntValue(namespace, "numColumns", 1); 
     } 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 

     setVerticalSpacing(getVerticleSpacing()); 
     if (isExpandFully) { 
      try { 
       if (getCount() != old_count) { 
        old_count = getCount(); 
        params = getLayoutParams(); 

        int len = (getCount() % getNumColumns() == 0 ? getCount()/getNumColumns() : getCount()/getNumColumns() + 1); 
        params.height = 0; 
        for (int i = 0; i < len; i++) { 
         params.height = params.height + (old_count > 0 ? getChildAt(0).getHeight() + getVerticleSpacing() : 0); 
        } 
        params.height += 10; 
        setLayoutParams(params); 
       } 
      } catch (Exception e) { 
      } 
     } 
     super.onDraw(canvas); 
    } 

} 

как использовать

CustomGridView myGridview = (CustomGridView)findViewById(R.id.customGridview); 

myGridview.setExpandFully(true); 
+0

Спасибо за это, но делает эту работу, если GridView находится внутри ScrollView? Поскольку основная причина этого вопроса заключается в том, что я должен перейти на высоту содержимого, чтобы прокручивающая часть была занята ScrollView, и сейчас это не работает, когда я ее применял. –

+0

да, это работает со мной. Я использовал это gridview в listview. –

+0

Как я применил это, казалось, что единственное, что показано в GridView, это первая строка. Сам GridView не расширен и не прокручивается. Может быть, разница в том, что я разместил GridView внутри ScrollView, а не ListView? –

Смежные вопросы