android - listView点击展开收起实现

废话不多说, 上图:

android - listView点击展开收起实现_第1张图片
GIF.gif

上思路:
动态改变数据适配器中的getCount()方法的返回值;
点击刷新适配器中的数据;

注意:
1.这是在普通的布局中实现;
2.如需要在ScrollView中实现该功能, 需要解决嵌套产生的ListView条目显示不全问题;
3.请看下一篇文章介绍;

上代码:

代码01 - listview条目布局的xml:




    

    

效果图:

android - listView点击展开收起实现_第2张图片
ListView条目布局效果图.png

代码02 - mainActivity的布局文件xml:




    

    

    


效果图:

android - listView点击展开收起实现_第3张图片
MainActivity布局效果图.png

代码03 - MainActivity代码

package com.geaosu.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView list;
    private TextView loadMore;

    private String[] arr1 = {"geaosu01", "geaosu02", "geaosu03", "geaosu04", "geaosu05"};

    private boolean isShowMore = false;
    private MoreAdapter moreAdapter;
    private int mCount = 1;

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

        list = findViewById(R.id.list);
        moreAdapter = new MoreAdapter();
        list.setAdapter(moreAdapter);

        loadMore = findViewById(R.id.loadMore);
        loadMore.setOnClickListener(this);
        loadMore.setText("点击展开");

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.loadMore:
                if (isShowMore) {
                    loadMore.setText("点击展开");
                } else {
                    loadMore.setText("点击收起");
                }
                isShowMore = !isShowMore;
                moreAdapter.notifyDataSetChanged();
                break;
        }
    }

    private class MoreAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // 重点区域
            if (isShowMore) {
                return arr1.length;
            } else {
                return mCount;
            }
        }

        @Override
        public Object getItem(int i) {
            return arr1[i];
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View itemView = View.inflate(MainActivity.this, R.layout.item_list, null);

            TextView name = itemView.findViewById(R.id.name);
            ImageView icon = itemView.findViewById(R.id.icon);

            name.setText(arr1[i]);

            return itemView;

        }
    }
}

============== 结束 ==============

努力让世界变得更好 ------ geaosu

你可能感兴趣的:(android - listView点击展开收起实现)