Home Java javaTutorial Android realizes the left and right sliding switching function of the interface

Android realizes the left and right sliding switching function of the interface

Jan 14, 2017 am 11:50 AM

I believe that everyone must have used software such as mobile QQ and WeChat. When we use it, it is not difficult to find that switching the interface can not only be achieved by clicking on the page tab, but also by sliding left and right. Mr. Mouse has just started to learn Android. I always thought that sliding like this was very cool, and I really wanted to realize it myself. I believe that everyone, like Mr. Mouse, wants to learn how to implement it without waiting. OK, let me explain in detail how to implement this function.

First, let’s get to know the control ViewPager

ViewPager is a class in the android-support-v4.jar, an additional package that comes with the Android SDk, and can be used to switch between screens. The latest version of android-support-v4.jar can be searched online. After downloading it, we need to add it to the project.

XML layout

First, let’s take a look at the layout of the activity. I believe everyone can understand this layout. The first line has only two TextView page labels. As for the name, you don’t need to care about the name. Haha, the second line is the scroll bar when sliding the interface. Picture You have to select and add it to the drawable. The length should not be too long. The third line is the ViewPager for interface switching we want to implement:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
  android:layout_height="match_parent" tools:context=".MediaPlayerActivity">
  <LinearLayout
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="50.0dip"
    android:background="#FFFFFF"
    >
    <!--layout_weight这个属性为权重,让两个textview平分这个linearLayout-->
    <TextView
      android:id="@+id/videoLayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_weight="1.0"
      android:gravity="center"
      android:text="视频"
      android:textColor="#000000"
      android:textSize="20dip"
      android:background="@drawable/selector"/>
    <TextView
      android:id="@+id/musicLayout"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_weight="1.0"
      android:gravity="center"
      android:text="音乐"
      android:textColor="#000000"
      android:textSize="20dip"
      android:background="@drawable/selector"/>
  </LinearLayout>
  <ImageView
    android:layout_width="match_parent"
    android:layout_height="10dp"
    android:layout_below="@id/linearLayout"
    android:id="@+id/scrollbar"
    android:scaleType="matrix"
    android:src="@drawable/scrollbar"/>
  <android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/scrollbar">
  </android.support.v4.view.ViewPager>
</RelativeLayout>
Copy after login

I set the background property of TextView in the layout first, so that when it is pressed, its background color can be changed, and the color will be restored when it is released. The method is to create a selector.xml file in drawable and write the following code;

selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:state_pressed="true"
    android:drawable="@color/press" />
</selector>
Copy after login

Of course, you must first create a new colors.xml file in the values ​​folder and configure the color of press:

colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="press">#25fa55</color>
</resources>
Copy after login

After looking at the layout of the activity, let's take a look at the layout of the interface we want to switch. These two layout files only need to be created in the layout file. There is no need to create a new activity. For simplicity, we only set the background color here. You can see the effect during testing:
video_player.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#ad2929">
</RelativeLayout>
Copy after login

media_player.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#acbbcf">
</RelativeLayout>
Copy after login

Java code

package com.example.blacklotus.multimedia;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;
import java.util.ArrayList;
public class MediaPlayerActivity extends Activity implements View.OnClickListener{
  private ViewPager viewPager;
  private ArrayList<View> pageview;
  private TextView videoLayout;
  private TextView musicLayout;
  // 滚动条图片
  private ImageView scrollbar;
  // 滚动条初始偏移量
  private int offset = 0;
  // 当前页编号
  private int currIndex = 0;
  // 滚动条宽度
  private int bmpW;
  //一倍滚动量
  private int one;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_media_player);
    viewPager = (ViewPager) findViewById(R.id.viewPager);
    //查找布局文件用LayoutInflater.inflate
    LayoutInflater inflater =getLayoutInflater();
    View view1 = inflater.inflate(R.layout.video_player, null);
    View view2 = inflater.inflate(R.layout.media_player, null);
    videoLayout = (TextView)findViewById(R.id.videoLayout);
    musicLayout = (TextView)findViewById(R.id.musicLayout);
    scrollbar = (ImageView)findViewById(R.id.scrollbar);
    videoLayout.setOnClickListener(this);
    musicLayout.setOnClickListener(this);
    pageview =new ArrayList<View>();
    //添加想要切换的界面
    pageview.add(view1);
    pageview.add(view2);
    //数据适配器
    PagerAdapter mPagerAdapter = new PagerAdapter(){
      @Override
      //获取当前窗体界面数
      public int getCount() {
        // TODO Auto-generated method stub
        return pageview.size();
      }
      @Override
      //判断是否由对象生成界面
      public boolean isViewFromObject(View arg0, Object arg1) {
        // TODO Auto-generated method stub
        return arg0==arg1;
      }
      //使从ViewGroup中移出当前View
      public void destroyItem(View arg0, int arg1, Object arg2) {
        ((ViewPager) arg0).removeView(pageview.get(arg1));
      }
      //返回一个对象,这个对象表明了PagerAdapter适配器选择哪个对象放在当前的ViewPager中
      public Object instantiateItem(View arg0, int arg1){
        ((ViewPager)arg0).addView(pageview.get(arg1));
        return pageview.get(arg1);
      }
    };
    //绑定适配器
    viewPager.setAdapter(mPagerAdapter);
    //设置viewPager的初始界面为第一个界面
    viewPager.setCurrentItem(0);
    //添加切换界面的监听器
    viewPager.addOnPageChangeListener(new MyOnPageChangeListener());
    // 获取滚动条的宽度
    bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.scrollbar).getWidth();
    //为了获取屏幕宽度,新建一个DisplayMetrics对象
    DisplayMetrics displayMetrics = new DisplayMetrics();
    //将当前窗口的一些信息放在DisplayMetrics类中
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    //得到屏幕的宽度
    int screenW = displayMetrics.widthPixels;
    //计算出滚动条初始的偏移量
    offset = (screenW / 2 - bmpW) / 2;
    //计算出切换一个界面时,滚动条的位移量
    one = offset * 2 + bmpW;
    Matrix matrix = new Matrix();
    matrix.postTranslate(offset, 0);
    //将滚动条的初始位置设置成与左边界间隔一个offset
    scrollbar.setImageMatrix(matrix);
  }
  public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
    @Override
    public void onPageSelected(int arg0) {
      Animation animation = null;
      switch (arg0) {
        case 0:
            /**
             * TranslateAnimation的四个属性分别为
             * float fromXDelta 动画开始的点离当前View X坐标上的差值 
             * float toXDelta 动画结束的点离当前View X坐标上的差值 
             * float fromYDelta 动画开始的点离当前View Y坐标上的差值 
             * float toYDelta 动画开始的点离当前View Y坐标上的差值
            **/
            animation = new TranslateAnimation(one, 0, 0, 0);
          break;
        case 1:
            animation = new TranslateAnimation(offset, one, 0, 0);
          break;
      }
      //arg0为切换到的页的编码
      currIndex = arg0;
      // 将此属性设置为true可以使得图片停在动画结束时的位置
      animation.setFillAfter(true);
      //动画持续时间,单位为毫秒
      animation.setDuration(200);
      //滚动条开始动画
      scrollbar.startAnimation(animation);
    }
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }
    @Override
    public void onPageScrollStateChanged(int arg0) {
    }
  }
  @Override
  public void onClick(View view){
     switch (view.getId()){
       case R.id.videoLayout:
         //点击"视频“时切换到第一页
         viewPager.setCurrentItem(0);
         break;
       case R.id.musicLayout:
         //点击“音乐”时切换的第二页
         viewPager.setCurrentItem(1);
         break;
     }
  }
}
Copy after login

OK, the above is all the code. Mr. Mouse has commented in the code in great detail. I believe everyone can understand it. Do you think it is very simple? Such a "cool" effect is achieved in this way, haha. If you want to create more pages, you can, but you have to deal with the sliding distance. If you still have any questions, you can ask Mr. Mouse at any time; if there are any mistakes in the above, please correct me and let us learn and improve together!

For more articles related to Android's implementation of the left and right sliding switching function of the interface, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles