溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Android如何實(shí)現(xiàn)列表元素動(dòng)態(tài)效果

發(fā)布時(shí)間:2022-03-29 15:26:14 來(lái)源:億速云 閱讀:332 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹了Android如何實(shí)現(xiàn)列表元素動(dòng)態(tài)效果的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Android如何實(shí)現(xiàn)列表元素動(dòng)態(tài)效果文章都會(huì)有所收獲,下面我們一起來(lái)看看吧。

前言

列表是移動(dòng)應(yīng)用中用得最多的組件了,我們也會(huì)經(jīng)常對(duì)列表元素進(jìn)行增加或刪除操作,最簡(jiǎn)單的方法是列表數(shù)據(jù)變動(dòng)后,直接 setState 更新列表界面。這種方式存在一個(gè)缺陷就是列表元素會(huì)突然消失(刪除)或出現(xiàn)(添加),當(dāng)列表元素內(nèi)容接近時(shí),我們都沒(méi)法知道操作是否成功了。而如果能夠有動(dòng)效展示這個(gè)消失和出現(xiàn)的過(guò)程,那么體驗(yàn)就會(huì)好很多,比如下面的這種效果,刪除元素的時(shí)候,會(huì)有個(gè)逐漸消失的動(dòng)畫(huà),而添加元素的時(shí)候會(huì)有漸現(xiàn)效果。

Android如何實(shí)現(xiàn)列表元素動(dòng)態(tài)效果

AnimatedList.gif

這里使用到的就是 AnimatedList,本篇文章的示例代碼主要來(lái)自官方文檔:AnimatedList 組件。需要注意的是,畢竟列表帶了動(dòng)畫(huà)效果,對(duì)性能肯定會(huì)有影響,建議只對(duì)需要對(duì)元素進(jìn)行刪除、增加操作的小數(shù)據(jù)量的列表使用。

AnimatedList 介紹

AnimatedList 是 ListView 的替代,構(gòu)造函數(shù)基本上和 ListView 一致。

const AnimatedList({
  Key? key,
  required this.itemBuilder,
  this.initialItemCount = 0,
  this.scrollDirection = Axis.vertical,
  this.reverse = false,
  this.controller,
  this.primary,
  this.physics,
  this.shrinkWrap = false,
  this.padding,
  this.clipBehavior = Clip.hardEdge,
})

不同的地方在于 itemBuilder 的定義不同,itemBuilder 與 ListView 相比,多了一個(gè) animation 參數(shù):

typedef AnimatedListItemBuilder = Widget Function(
  BuildContext context, 
  int index, 
  Animation<double> animation
);

animation是一個(gè) Animation<double>對(duì)象,因此可以使用 animation 來(lái)構(gòu)建元素的過(guò)渡動(dòng)畫(huà)。比如我們這里的示例就使用了 FadeTransition 來(lái)構(gòu)建列表元素,從而有漸現(xiàn)效果。

class ListItem extends StatelessWidget {
  const ListItem({
    Key? key,
    required this.onRemove,
    required this.animation,
    required this.item,
  }) : super(key: key);

  final Animation<double> animation;
  final ValueChanged onRemove;
  final int item;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(2.0),
      child: FadeTransition(
        opacity: animation,
        child: Container(
          child: Row(children: [
            Expanded(
              child: Text(
                'Item $item',
                style: TextStyle(
                  color: Colors.blue,
                ),
              ),
            ),
            IconButton(
              onPressed: () {
                onRemove(this.item);
              },
              icon: Icon(Icons.delete_forever_rounded, color: Colors.grey),
            ),
          ]),
        ),
      ),
    );
  }
}

元素的插入和刪除

使用 AnimatedList 時(shí),我們需要調(diào)用 AnimatedListState 的insertItem 和 removeItem 方法來(lái)操作,而不能直接操作完數(shù)據(jù)后刷新界面。也就是在插入和刪除數(shù)據(jù)的時(shí)候,應(yīng)該是先修改列表數(shù)據(jù),然后再調(diào)用AnimatedListState的 insertItem 或 removeItem 方法來(lái)刷新列表界面。例如刪除元素的代碼:

E removeAt(int index) {
  final E removedItem = _items.removeAt(index);

  if (removedItem != null) {
    _animatedList!.removeItem(
      index,
      (BuildContext context, Animation<double> animation) {
        return removedItemBuilder(removedItem, context, animation);
      },
    );
  }
  return removedItem;
}

這里 removedItem接收兩個(gè)參數(shù),一個(gè)是要移除元素的下標(biāo),另一個(gè)是一個(gè)構(gòu)建移除元素的方法 builder。之所以要這個(gè)方法是因?yàn)樵貙?shí)際從列表馬上移除的,為了在動(dòng)畫(huà)過(guò)渡時(shí)間內(nèi)還能夠看到被移除的元素,需要通過(guò)這種方式來(lái)構(gòu)建一個(gè)被移除的元素來(lái)感覺(jué)是動(dòng)畫(huà)刪除的。這里也可以使用 animation 參數(shù)自定義動(dòng)畫(huà)效果。insertItem 方法沒(méi)有 builder 參數(shù),它直接將新插入的元素傳給 AnimatedList 的 builder 方法來(lái)插入新的元素,這樣能夠保持和列表新增元素的動(dòng)效一致。

使用 GlobalKey 獲取 AnimatedListState

由于 AnimatedList 的所有控制都是在 AnimatedState 中進(jìn)行的,而 AnimatedState 對(duì)象沒(méi)法直接獲取得到,因此需要使用 GlobalKey 來(lái)獲取 AnimatedListState 對(duì)象。在構(gòu)建 AnimatedList 的時(shí)候給 key 屬性傳入一個(gè) GlobalKey,。然后就可以通過(guò) currentState 獲取到 AnimatedListState 對(duì)象了。

class _AnimatedListSampleState extends State<AnimatedListSample> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
  late ListModel<int> _list;
  late int _nextItem;

  @override
  void initState() {
    super.initState();
    _list = ListModel<int>(
      listKey: _listKey,
      initialItems: <int>[0, 1, 2],
      removedItemBuilder: _buildRemovedItem,
    );
    _nextItem = 3;
  }

  Widget _buildRemovedItem(
      int item, BuildContext context, Animation<double> animation) {
    return ListItem(
      animation: animation,
      item: item,
      onRemove: _remove,
    );
  }

  // Insert the "next item" into the list model.
  void _insert() {
    final int index = _list.length;
    _list.insert(index, _nextItem++);
  }

  // Remove the selected item from the list model.
  void _remove(item) {
    if (item != null) {
      _list.removeAt(_list.indexOf(item!));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AnimatedList'),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: _insert,
            tooltip: '添加',
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: AnimatedList(
          key: _listKey,
          initialItemCount: _list.length,
          itemBuilder: (context, index, animation) {
            return FadeTransition(
              opacity: animation,
              child: ListItem(
                onRemove: _remove,
                animation: animation,
                item: _list[index],
              ),
            );
          },
        ),
      ),
    );
  }
}

關(guān)于“Android如何實(shí)現(xiàn)列表元素動(dòng)態(tài)效果”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“Android如何實(shí)現(xiàn)列表元素動(dòng)態(tài)效果”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI