自定義可適應(yīng)ScrollView的ListView
這個方法和上面的方法是異曲同工侦讨,方法3是自定義了LinearLayout以取代ListView的功能摧找,但如果我脾氣就是倔养交,就是要用ListView怎么辦抓狭?那就只好自定義一個類繼承自ListView,通過重寫其onMeasure方法线欲,達到對ScrollView適配的效果明场。
下面是繼承了ListView的自定義類:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class ListViewForScrollView extends ListView {
public ListViewForScrollView(Context context) {
super(context);
}
public ListViewForScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ListViewForScrollView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
@Override
/**
* 重寫該方法,達到使ListView適應(yīng)ScrollView的效果
*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
三個構(gòu)造方法完全不用動李丰,只要重寫onMeasure方法苦锨,需要改動的地方比起方法3少了不是一點半點…
在xml布局中和Activty中使用的ListView改成這個自定義ListView就行了。代碼就省了吧…
這個方法和方法1有一個同樣的毛病趴泌,就是默認顯示的首項是ListView舟舒,需要手動把ScrollView滾動至最頂端。
sv = (ScrollView) findViewById(R.id.act_solution_4_sv);
sv.smoothScrollTo(0, 0);