//建立函數將dp轉換為像素
public int Dp2Px(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
//建立函數動態設定ListView的高度
public void setListViewHeightBasedOnChildren(ListView listView) {
//取得ListView的Adapter
ListAdapter listAdapter = listView.getAdapter();
//固定每一行的高度
int itemHeight = 50;
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
totalHeight += Dp2Px(getApplicationContext(),itemHeight)+listView.getDividerHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight;
listView.setLayoutParams(params);
}
使用時將ListView傳入
ListView lv_set_meal = (ListView) findViewById (R.id.lv_set_meal);
Adapter_ListView adapter = new Adapter_ListView(context, arraySetMeal_item);
lv_set_meal.setAdapter(adapter);
setListViewHeightBasedOnChildren(lv_set_meal);// 必須放在setAdapter後面
沒有留言:
張貼留言