使用SlidingPaneLayout实现左滑菜单

2024-05-06 20:48

本文主要是介绍使用SlidingPaneLayout实现左滑菜单,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

众所周知,在Google的Support包中发布了众多令人激动的控件,大大方便了我们实现界面效果,提高开发效率,今天我们来学习一下SlidingPaneLayout
SlidingPaneLayout位于SupportV4包中,要使用它,我们首先要在build.gradle文件中添加项目依赖,如下所示:

compile 'com.android.support:support-v4:25.1.0'

等待项目重新构建完成后,我们就可以在XML布局文件中使用它了,具体书写方法如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SlidingPaneLayout
    xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/spl_root"android:layout_width="match_parent"android:layout_height="match_parent"> 
</android.support.v4.widget.SlidingPaneLayout>

在这里,我们需要注意一点,SlidingPaneLayout需要一个指定的宽度去适配布局,一般使用match_parent

接下来我们为SlidingPaneLayout添加两个pane,看看大概的效果:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SlidingPaneLayout
    xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/spl_root"android:layout_width="match_parent"android:layout_height="match_parent"><TextView
        android:id="@+id/tv_left"android:layout_width="120dp"android:layout_height="match_parent"android:text="左侧菜单"android:textSize="22sp"android:background="#ff0000"/><TextView
        android:id="@+id/tv_right"android:layout_width="match_parent"android:layout_height="match_parent"android:text="这是内容"android:textSize="24sp"android:background="@color/colorPrimaryDark"/>
</android.support.v4.widget.SlidingPaneLayout>

随后运行项目,效果如下图:
这里写图片描述
随后我们使用ListView搭配ScrollView来实现一种常见的左列表,右侧详情页的效果:
修改布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SlidingPaneLayout
    xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/sliding_pane_layout"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.example.tuozhaobing.slidingpanedemo.MainActivity"><ListView
        android:id="@+id/left_pane"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginRight="0dp"android:paddingRight="0dp"android:layout_gravity="left"></ListView><ScrollView
        android:layout_width="match_parent"android:layout_height="match_parent"android:scrollbarStyle="outsideOverlay"android:background="#ff333333"><TextView
            android:id="@+id/content_text"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="@string/sliding_pane_layout_summary"android:textAppearance="?android:attr/textAppearanceMedium"/></ScrollView></android.support.v4.widget.SlidingPaneLayout>

随后修改MainActivity.java代码如下:

package com.example.tuozhaobing.slidingpanedemo;import android.support.v4.widget.SlidingPaneLayout;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;public class MainActivity extends AppCompatActivity {private SlidingPaneLayout mSlidingPaneLayout;private ListView mListView;private TextView mTextView;public static final String[] TITLES ={"Henry IV (1)","Henry V","Henry VIII","Richard II","Richard III","Merchant of Venice","Othello","King Lear"};public static final String[] DIALOGUE ={"So shaken as we are, so wan with care," +"Find we a time for frighted peace to pant," +"And breathe short-winded accents of new broils" +"To be commenced in strands afar remote." +"No more the thirsty entrance of this soil" +"Shall daub her lips with her own children's blood;" +"Nor more shall trenching war channel her fields," +"Nor bruise her flowerets with the armed hoofs" +"Of hostile paces: those opposed eyes," +"Which, like the meteors of a troubled heaven," +"All of one nature, of one substance bred," +"Did lately meet in the intestine shock" +"And furious close of civil butchery" +"Shall now, in mutual well-beseeming ranks," +"March all one way and be no more opposed" +"Against acquaintance, kindred and allies:" +"The edge of war, like an ill-sheathed knife," +"No more shall cut his master. Therefore, friends," +"As far as to the sepulchre of Christ," +"Whose soldier now, under whose blessed cross" +"We are impressed and engaged to fight," +"Forthwith a power of English shall we levy;" +"Whose arms were moulded in their mothers' womb" +"To chase these pagans in those holy fields" +"Over whose acres walk'd those blessed feet" +"Which fourteen hundred years ago were nail'd" +"For our advantage on the bitter cross." +"But this our purpose now is twelve month old," +"And bootless 'tis to tell you we will go:" +"Therefore we meet not now. Then let me hear" +"Of you, my gentle cousin Westmoreland," +"What yesternight our council did decree" +"In forwarding this dear expedience.","Hear him but reason in divinity," +"And all-admiring with an inward wish" +"You would desire the king were made a prelate:" +"Hear him debate of commonwealth affairs," +"You would say it hath been all in all his study:" +"List his discourse of war, and you shall hear" +"A fearful battle render'd you in music:" +"Turn him to any cause of policy," +"The Gordian knot of it he will unloose," +"Familiar as his garter: that, when he speaks," +"The air, a charter'd libertine, is still," +"And the mute wonder lurketh in men's ears," +"To steal his sweet and honey'd sentences;" +"So that the art and practic part of life" +"Must be the mistress to this theoric:" +"Which is a wonder how his grace should glean it," +"Since his addiction was to courses vain," +"His companies unletter'd, rude and shallow," +"His hours fill'd up with riots, banquets, sports," +"And never noted in him any study," +"Any retirement, any sequestration" +"From open haunts and popularity.","I come no more to make you laugh: things now," +"That bear a weighty and a serious brow," +"Sad, high, and working, full of state and woe," +"Such noble scenes as draw the eye to flow," +"We now present. Those that can pity, here" +"May, if they think it well, let fall a tear;" +"The subject will deserve it. Such as give" +"Their money out of hope they may believe," +"May here find truth too. Those that come to see" +"Only a show or two, and so agree" +"The play may pass, if they be still and willing," +"I'll undertake may see away their shilling" +"Richly in two short hours. Only they" +"That come to hear a merry bawdy play," +"A noise of targets, or to see a fellow" +"In a long motley coat guarded with yellow," +"Will be deceived; for, gentle hearers, know," +"To rank our chosen truth with such a show" +"As fool and fight is, beside forfeiting" +"Our own brains, and the opinion that we bring," +"To make that only true we now intend," +"Will leave us never an understanding friend." +"Therefore, for goodness' sake, and as you are known" +"The first and happiest hearers of the town," +"Be sad, as we would make ye: think ye see" +"The very persons of our noble story" +"As they were living; think you see them great," +"And follow'd with the general throng and sweat" +"Of thousand friends; then in a moment, see" +"How soon this mightiness meets misery:" +"And, if you can be merry then, I'll say" +"A man may weep upon his wedding-day.","First, heaven be the record to my speech!" +"In the devotion of a subject's love," +"Tendering the precious safety of my prince," +"And free from other misbegotten hate," +"Come I appellant to this princely presence." +"Now, Thomas Mowbray, do I turn to thee," +"And mark my greeting well; for what I speak" +"My body shall make good upon this earth," +"Or my divine soul answer it in heaven." +"Thou art a traitor and a miscreant," +"Too good to be so and too bad to live," +"Since the more fair and crystal is the sky," +"The uglier seem the clouds that in it fly." +"Once more, the more to aggravate the note," +"With a foul traitor's name stuff I thy throat;" +"And wish, so please my sovereign, ere I move," +"What my tongue speaks my right drawn sword may prove.","Now is the winter of our discontent" +"Made glorious summer by this sun of York;" +"And all the clouds that lour'd upon our house" +"In the deep bosom of the ocean buried." +"Now are our brows bound with victorious wreaths;" +"Our bruised arms hung up for monuments;" +"Our stern alarums changed to merry meetings," +"Our dreadful marches to delightful measures." +"Grim-visaged war hath smooth'd his wrinkled front;" +"And now, instead of mounting barded steeds" +"To fright the souls of fearful adversaries," +"He capers nimbly in a lady's chamber" +"To the lascivious pleasing of a lute." +"But I, that am not shaped for sportive tricks," +"Nor made to court an amorous looking-glass;" +"I, that am rudely stamp'd, and want love's majesty" +"To strut before a wanton ambling nymph;" +"I, that am curtail'd of this fair proportion," +"Cheated of feature by dissembling nature," +"Deformed, unfinish'd, sent before my time" +"Into this breathing world, scarce half made up," +"And that so lamely and unfashionable" +"That dogs bark at me as I halt by them;" +"Why, I, in this weak piping time of peace," +"Have no delight to pass away the time," +"Unless to spy my shadow in the sun" +"And descant on mine own deformity:" +"And therefore, since I cannot prove a lover," +"To entertain these fair well-spoken days," +"I am determined to prove a villain" +"And hate the idle pleasures of these days." +"Plots have I laid, inductions dangerous," +"By drunken prophecies, libels and dreams," +"To set my brother Clarence and the king" +"In deadly hate the one against the other:" +"And if King Edward be as true and just" +"As I am subtle, false and treacherous," +"This day should Clarence closely be mew'd up," +"About a prophecy, which says that 'G'" +"Of Edward's heirs the murderer shall be." +"Dive, thoughts, down to my soul: here" +"Clarence comes.","To bait fish withal: if it will feed nothing else," +"it will feed my revenge. He hath disgraced me, and" +"hindered me half a million; laughed at my losses," +"mocked at my gains, scorned my nation, thwarted my" +"bargains, cooled my friends, heated mine" +"enemies; and what's his reason? I am a Jew. Hath" +"not a Jew eyes? hath not a Jew hands, organs," +"dimensions, senses, affections, passions? fed with" +"the same food, hurt with the same weapons, subject" +"to the same diseases, healed by the same means," +"warmed and cooled by the same winter and summer, as" +"a Christian is? If you prick us, do we not bleed?" +"if you tickle us, do we not laugh? if you poison" +"us, do we not die? and if you wrong us, shall we not" +"revenge? If we are like you in the rest, we will" +"resemble you in that. If a Jew wrong a Christian," +"what is his humility? Revenge. If a Christian" +"wrong a Jew, what should his sufferance be by" +"Christian example? Why, revenge. The villany you" +"teach me, I will execute, and it shall go hard but I" +"will better the instruction.","Virtue! a fig! 'tis in ourselves that we are thus" +"or thus. Our bodies are our gardens, to the which" +"our wills are gardeners: so that if we will plant" +"nettles, or sow lettuce, set hyssop and weed up" +"thyme, supply it with one gender of herbs, or" +"distract it with many, either to have it sterile" +"with idleness, or manured with industry, why, the" +"power and corrigible authority of this lies in our" +"wills. If the balance of our lives had not one" +"scale of reason to poise another of sensuality, the" +"blood and baseness of our natures would conduct us" +"to most preposterous conclusions: but we have" +"reason to cool our raging motions, our carnal" +"stings, our unbitted lusts, whereof I take this that" +"you call love to be a sect or scion.","Blow, winds, and crack your cheeks! rage! blow!" +"You cataracts and hurricanoes, spout" +"Till you have drench'd our steeples, drown'd the cocks!" +"You sulphurous and thought-executing fires," +"Vaunt-couriers to oak-cleaving thunderbolts," +"Singe my white head! And thou, all-shaking thunder," +"Smite flat the thick rotundity o' the world!" +"Crack nature's moulds, an germens spill at once," +"That make ingrateful man!"};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();initData();}private void initData() {mSlidingPaneLayout.closePane();mSlidingPaneLayout.getViewTreeObserver().addOnGlobalLayoutListener(new FirstLayoutListener());mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, TITLES));mListView.setOnItemClickListener(new ListItemClickListener());}private void initView() {mSlidingPaneLayout = (SlidingPaneLayout) findViewById(R.id.sliding_pane_layout);mListView = (ListView) findViewById(R.id.left_pane);mTextView = (TextView) findViewById(R.id.content_text);}public class ListItemClickListener implements AdapterView.OnItemClickListener{@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {mTextView.setText(DIALOGUE[position]);
//            mActionBar.setTitle(TITLES[position]);mSlidingPaneLayout.closePane();}}public class FirstLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener{@Overridepublic void onGlobalLayout() {mSlidingPaneLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);}}
}

运行项目,效果如下:
这里写图片描述

最新文章更新在微信公众号上,欢迎关注获取详情:
这里写图片描述

这篇关于使用SlidingPaneLayout实现左滑菜单的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/965344

相关文章

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

使用IDEA部署Docker应用指南分享

《使用IDEA部署Docker应用指南分享》本文介绍了使用IDEA部署Docker应用的四步流程:创建Dockerfile、配置IDEADocker连接、设置运行调试环境、构建运行镜像,并强调需准备本... 目录一、创建 dockerfile 配置文件二、配置 IDEA 的 Docker 连接三、配置 Do

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统