ScrollView中添加ListView

Mexican 2011-11-21

1.要点一:去除ListView的scrollBar,添加ScrollView的scrollBar:
<ScrollView android:layout_width="fill_parent"
            android:layout_height="wrap_content" 
            android:layout_weight="1" 
            android:scrollbars="vertical">
       <LinearLayout android:orientation="vertical" 
                     android:layout_width="fill_parent" 
                     android:layout_height="wrap_content">
            <LinearLayout android:layout_width="fill_parent"
                          android:layout_height="wrap_content"
                          android:orientation="horizontal" 
                          android:paddingLeft="5dp" android:paddingRight="5dp" 
                          android:paddingTop="6dp" android:paddingBottom="6dp"                           

android:background="@color/LightSteelBlue1">
           		
            	 <TextView android:id="@+id/text" android:text="列表如下:" 
                           android:layout_width="wrap_content"  android:layout_height="wrap_content"                

            android:textColor="@color/White" android:layout_marginLeft="10dp"                                       

            android:gravity="center_horizontal" 
                           android:paddingTop="5dp" android:paddingBottom="5dp" android:clickable="true"/>
           </LinearLayout>
           <ListView android:id="@+id/list_alarm" android:layout_width="fill_parent" 
                     android:layout_height="wrap_content" android:layout_weight="1" 
                     android:cacheColorHint="@color/LightCyan2" android:scrollbars="none"/>  
      </LinearLayout>
</ScrollView>

 2.要点二:(设置ListView的高度,否则只能显示1-2行)

在setAdapter之后,在设置ListView的高度(不是wrap_content),其高度 = 每行高度 * 行数 + 行间距 * (行数 - 1),用ViewGroup.LayoutParams 设置ListView 的高度

private void setAdapter(){
		ArrayAdapter<String> adapter = new ArrayAdapter<String>

(MainActivity.this,android.R.layout.simple_list_item_1,listSource);
		mListView.setAdapter(adapter);
		setLvHeight();
	}
	
	private void setLvHeight(){
		ListAdapter adapter = mListView.getAdapter();
		if(adapter == null){
			ShowLog.d(TAG, "no data in ListView");
			return;
		}
		int totalHeight = 0;
		for(int i = 0;i < adapter.getCount(); i++){
			View itemView = adapter.getView(i, null, mListView);
			itemView.measure(0, 0);
			totalHeight += itemView.getMeasuredHeight();
		}
		ViewGroup.LayoutParams layoutParams = mListView.getLayoutParams();
		layoutParams.height = totalHeight + (mListView.getDividerHeight() * (adapter.getCount() - 1));//总行高+每行的间距
		mListView_Alarm.setLayoutParams(layoutParams);
	}

相关推荐

ALDRIDGE / 0评论 2011-09-29