2015-05-04 17 views
4

擁有listView,如果它的內容較少,那麼它的高度應該與"wrap_content"一致。如果它有更多的行,最大高度應該限制在某個高度。是否可以在xml中設置listView maxHeight?

它允許設置android:maxHeightListView

<ListView> 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:maxHeight="120dp" 
</ListView> 

,但它不工作,始終"wrap_content"。 有隻讓它的工作方式是在代碼中使用

int cHeight = parentContainer.getHeight(); 
ViewGroup.LayoutParams lp = mListView.getLayoutParams(); 

if (messageListRow > n) 
{ 
    lp.height = (int)(cHeight * 0.333); 
} 
else 
{ 
    lp.height = ViewGroup.LayoutParams.WRAP_CONTENT; 
} 

mListView.setLayoutParams(lp); 

有沒有辦法做到這一點的XML?

+1

請勿將「wrap_content」用於listview的高度,因爲這會導致您的適配器被多次調用。爲什麼不把你的listview放在LinearLayout容器中,而是根據你的需求來控制高度。 – Pztar

+0

好點,謝謝Pztar。但即使放入LinearLayout容器,定義容器的高度仍然是個問題。也許動態設置代碼是唯一的方法。 – lannyf

回答

8

是的,你可以有你的自定義ListViewmaxHeight財產。

步驟1.創建attrs.xml文件values文件夾內,並把以下代碼:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 

    <declare-styleable name="ListViewMaxHeight"> 
     <attr name="maxHeight" format="dimension" /> 
    </declare-styleable> 

</resources> 

步驟2.創建新類(ListViewMaxHeight.java)和延伸ListView類:

package com.example.myapp; 

import android.content.Context; 
import android.content.res.TypedArray; 
import android.util.AttributeSet; 
import android.widget.ListView; 

public class ListViewMaxHeight extends ListView { 

    private final int maxHeight; 

    public ListViewMaxHeight(Context context) { 
     this(context, null); 
    } 

    public ListViewMaxHeight(Context context, AttributeSet attrs) { 
     this(context, attrs, 0); 
    } 

    public ListViewMaxHeight(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
     if (attrs != null) { 
      TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ListViewMaxHeight); 
      maxHeight = a.getDimensionPixelSize(R.styleable.ListViewMaxHeight_maxHeight, Integer.MAX_VALUE); 
      a.recycle(); 
     } else { 
      maxHeight = 0; 
     } 
    } 

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     int measuredHeight = MeasureSpec.getSize(heightMeasureSpec); 
     if (maxHeight > 0 && maxHeight < measuredHeight) { 
      int measureMode = MeasureSpec.getMode(heightMeasureSpec); 
      heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, measureMode); 
     } 
     super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
    } 

} 

步驟3.在您的佈局的xml文件中:

<com.example.myapp.ListViewMaxHeight 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      app:maxHeight="120dp" /> 
+0

這不是一個好的解決方案。 我用它和我的適配器,我看到'位置'項沒有真正的價值。 – Seyyed

相關問題