自定義可適應(yīng)ScrollView的ListView
這個方法和上面的方法是異曲同工,方法3是自定義了LinearLayout以取代ListView的功能,但如果我脾氣就是倔,就是要用ListView怎么辦?那就只好自定義一個類繼承自ListView,通過重寫其onMeasure方法,達(dá)到對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
/**
* 重寫該方法,達(dá)到使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少了不是一點(diǎn)半點(diǎn)…
在xml布局中和Activty中使用的ListView改成這個自定義ListView就行了。代碼就省了吧…
這個方法和方法1有一個同樣的毛病,就是默認(rèn)顯示的首項是ListView,需要手動把ScrollView滾動至最頂端。
sv = (ScrollView) findViewById(R.id.act_solution_4_sv);
sv.smoothScrollTo(0, 0);