效果图:
Android实现 ScrollView+ListView无滚动条滚动,即ListView的数据会全部显示完,但Listview无滚动条。
核心代码如下:
1. NoScrollListView.java
- /***
- * 自定义ListView子类,继承ListView
- * @author Administrator
- *
- */
- public class NoScrollListView extends ListView {
- public NoScrollListView(Context context) {
- super(context);
- }
- public NoScrollListView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
- public NoScrollListView(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
- @Override
- public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
- super.onMeasure(widthMeasureSpec, expandSpec);
- }
- }
2. res > layout > activity_main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/ScrollView"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="#FFF4F4F4"
- android:scrollbars="vertical" >
- <LinearLayout
- android:id="@+id/LinearLayout"
- android:gravity="center_horizontal"
- android:background="#FFF4F4F4"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <TextView
- android:id="@+id/textView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginLeft="2dp"
- android:layout_marginTop="20dp"
- android:text="This's a listView..." />
- <!--原: <ListView> -->
- <com.example.listviewdemo.NoScrollListView
- android:id="@+id/listView1"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:dividerHeight="0.0dip"
- android:fadingEdge="none"
- android:cacheColorHint="#FFF4F4F4"/>
- </LinearLayout>
- </ScrollView>
3.MainActivity
- private String[] nameList = {"Miley Cyruc","Alice Keys","Jewel","Dublin","Kelly Clarkson",
- "Mariah Carey","Sheen","Adele","Avril Lavigne","Taylor Swift"};
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- ListView lv = (ListView) findViewById(R.id.listView1);
- ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, nameList);
- lv.setAdapter(adapter);
- //lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);//选择效果
- //listView注册一个元素点击事件监听器
- lv.setOnItemClickListener(new OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
- Log.d(TAG, "//:"+MainActivity.this.nameList[arg2]);
- Toast.makeText(MainActivity.this, "Hey, "+nameList[arg2], Toast.LENGTH_LONG).show();
- }
- });
- }