Android自定义ListView示例,以创建不可滚动的ListView

本教程介绍如何在Android应用中创建不可滚动的ListView。由于ListView的滚动与ScrollView冲突,我们通过创建自定义ListView类NonScrollListView并在onMeasure()方法中进行调整,使ListView不再滚动。同时展示了使用Butterknife绑定视图的代码示例和最终应用的输出效果。
摘要由CSDN通过智能技术生成

In this tutorial we’ll override the ListView class to suit it according to our requirements in the android application.

在本教程中,我们将根据Android应用程序中的要求覆盖ListView类以使其适合您。

Android非滚动ListView要求 (Android Non Scrollable ListView Requirement)

A ListView comes up with its own default scrolling methods. Now if we wish to create a layout which contains a ListView along with some other views inside a parent ScrollView then you’ll notice that the scrolling gestures of the ListView don’t work as desired.

ListView带有其自己的默认滚动方法。 现在,如果我们希望创建一个包含ListView以及父ScrollView内其他视图的布局,那么您会注意到ListView的滚动手势无法正常工作。

The reason for this is that scrolling gestures received by the layout, they are all handled by the parent layout only. One workaround is to add the other views as the headers and footers of the ListView and avoid using ListView and ScrollView. But a more robust option is to create custom ListView class to suit it to our needs by making it non scrollable.

这样做的原因是,布局接收到的滚动手势都仅由父布局处理。 一种解决方法是将其他视图添加为ListView的页眉和页脚,并避免使用ListView和ScrollView。 但是,更可靠的选择是创建自定义ListView类 ,使其成为不可滚动的,从而使其满足我们的需求。

In this tutorial we’ll develop a custom ListView class and use it in a ScrollView with other child views. We’ll use Butterknife to bind the views.

在本教程中,我们将开发一个自定义ListView类,并将其在ScrollView中与其他子视图一起使用。 我们将使用Butterknife绑定视图。

项目结构 (Project Structure)

The project consists of a MainActivity and a subclass of ListView named NonScrollListView.

该项目包含一个MainActivity和一个名为NonScrollListView的ListView子类。

(Code)

The NonScrollListView class is given below:

下面给出了NonScrollListView类:

public class NonScrollListView extends ListView {

    public NonScrollListView(Context context) {
        super(context);
    }
    public NonScrollListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
        ViewGroup.LayoutParams params = getLayoutParams();
        params.height = getMeasuredHeight();
    }
}

onMeasure() allows us to specify how big you want your custom view to be with respect to the layout constraints of the parent class. AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value.

onMeasure()允许我们相对于父类的布局约束指定您希望自定义视图的大小。 AT_MOST通常表示layout_widthlayout_heigh吨值设定为match_parentwrap_content其中需要的最大尺寸(这是布局依赖于框架),并且父维度的大小的值。

The layout of the MainActivity is given below:
activity_main.xml

MainActivity的布局如下:
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

    <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/header_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:background="#36D2AA"
            android:padding="@dimen/activity_horizontal_margin"
            android:text="Header Button" />

        <com.journaldev.nonscrollablelistview.NonScrollListView
            android:id="@+id/listView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/header_button"></com.journaldev.nonscrollablelistview.NonScrollListView>

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/button2"
            android:padding="@dimen/activity_horizontal_margin"
            android:text="Footer Button 3" />

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/button1"
            android:padding="@dimen/activity_horizontal_margin"
            android:text="Footer Button 2" />

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/listView"
            android:text="Footer Button 1" />

    </RelativeLayout>
</ScrollView>

The package name of the custom ListView class is set as the tag. The layout consists of four buttons inside a RelativeLayout that’s the child of the a ScrollView.

自定义ListView类的包名称设置为标记。 布局由RelativeLayout内的四个按钮组成,它是ScrollView的子级。

The MainActivity.java is given below:

MainActivity.java如下所示:

package com.journaldev.nonscrollablelistview;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnItemClick;
import butterknife.OnItemSelected;

public class MainActivity extends AppCompatActivity {

    @InjectView(R.id.listView)
    NonScrollListView nonScrollListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);

        final List<String[]> values = new LinkedList<String[]>();
        values.add(new String[]{"Title 1", "Subtitle 1"});
        values.add(new String[]{"Title 2", "Subtitle 2"});
        values.add(new String[]{"Title 3", "Subtitle 3"});
        values.add(new String[]{"Title 4", "Subtitle 4"});
        values.add(new String[]{"Title 5", "Subtitle 5"});
        values.add(new String[]{"Title 6", "Subtitle 6"});
        values.add(new String[]{"Title 7", "Subtitle 7"});
        values.add(new String[]{"Title 8", "Subtitle 8"});

        nonScrollListView.setAdapter(new ArrayAdapter<String[]>(MainActivity.this, android.R.layout.simple_expandable_list_item_2, android.R.id.text1, values) {

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);

                String[] entry = values.get(position);
                TextView text1 = (TextView) view.findViewById(android.R.id.text1);
                TextView text2 = (TextView) view.findViewById(android.R.id.text2);
                text1.setText(entry[0]);
                text2.setText(entry[1]);

                return view;
            }
        });
    }

    @Nullable
    @OnClick({ R.id.header_button, R.id.button1,R.id.button2 , R.id.button3})
    public void commonMethod() {
        Toast.makeText(getApplicationContext(),"Button is clicked",Toast.LENGTH_SHORT).show();
    }

    @OnItemClick(R.id.listView)
    void onItemClick(int position) {
        Toast.makeText(getApplicationContext(),"Position "+position+" is clicked",Toast.LENGTH_SHORT).show();
    }

}

We’ve used a new default list layout android.R.layout.simple_expandable_list_item_2. It consists of two textViews that can be only invoked using ids : android.R.id.text1 and android.R.id.text2. The ListView is populated using a LinkedList of String arrays.

我们使用了新的默认列表布局android.R.layout.simple_expandable_list_item_2 。 它由两个只能使用id调用的textView组成: android.R.id.text1android.R.id.text2 。 使用String数组的LinkedList填充ListView。

The output of the application in action is given below:

实际应用程序的输出如下:

Note: Replace the NonScrollListView with a normal ListView in the xml and the code. The following output is returned.

注意 :将xml和代码中的NonScrollListView替换为普通的ListView。 返回以下输出。

As you can see the ListView default scrolls conflict with the ScrollView’s hence the gestures are not handled properly.

如您所见,ListView默认滚动与ScrollView冲突,因此手势处理不正确。

替代方式 (Alternate Way)

A workaround to the above problem without creating a custom widget is given below:

下面给出了不创建自定义窗口小部件的上述问题的解决方法:

listView.setOnTouchListener(new ListView.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            switch (action) {
            case MotionEvent.ACTION_DOWN:
                // Disallow ScrollView to intercept touch events.
                v.getParent().requestDisallowInterceptTouchEvent(true);
                break;

            case MotionEvent.ACTION_UP:
                // Allow ScrollView to intercept touch events.
                v.getParent().requestDisallowInterceptTouchEvent(false);
                break;
            }

            // Handle ListView touch events.
            v.onTouchEvent(event);
            return true;
        }
    });

This brings an end to this tutorial. You can download the final Android Custom Non Scrollable ListView Project from the link below.

本教程到此结束。 您可以从下面的链接下载最终的Android自定义非滚动ListView项目

翻译自: https://www.journaldev.com/10444/android-custom-listview-non-scrollable

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值