📜  如何创建Android应用程序的自定义简介滑块?

📅  最后修改于: 2021-05-13 14:44:44             🧑  作者: Mango

许多应用程序中的Intro Slider通常用于向用户介绍该应用程序,该应用程序的功能以及我们的应用程序将向我们提供的服务。在本文中,我们将研究应用程序中Custom Intro Slider的实现。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,其中将显示一个介绍性滑块,其中将在我们的应用程序中显示滑块。该滑块包含一个简单的图像和两个TextView。下面给出了一个示例GIF,以了解我们将在本文中做些什么。注意,我们将使用Java语言实现该项目。

创建Android应用示例GIF的自定义简介滑块

自定义介绍滑块的分步实现

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:在build.gradle文件中添加Picasso的依赖项

由于我们将从在线资源加载所有图像,因此我们将使用Picasso从应用程序内部的URL加载图像。因此,要使用来自URL的图像,我们必须在build.gradle文件中添加以下依赖项。

步骤3:为Internet添加权限

由于我们将从URL加载图像,因此我们必须在您的AndroidManifest.xml文件中添加Internet权限。用于添加权限。导航到应用程序> AndroidManifest.xml文件,然后添加以下权限。

步骤4:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。

XML


  
    
    
  
    
  
        
  
        
        
  
        
        


XML


  
    
    
  
    
    
  
    
    
  


Java
public class SliderModal {
  
    // string variable for storing 
    // title, image url and description.
    private String title;
    private String heading;
    private String imgUrl;
    private int backgroundDrawable;
  
    public SliderModal() {
        // empty constructor is required
        // when using firebase
    }
  
    // creating getter methods.
    public String getTitle() {
        return title;
    }
  
    public void setTitle(String title) {
        this.title = title;
    }
  
    public String getHeading() {
        return heading;
    }
  
    // creating setter methods
    public void setHeading(String heading) {
        this.heading = heading;
    }
  
    public String getImgUrl() {
        return imgUrl;
    }
  
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
      
    // constructor for our modal class
    public SliderModal(String title, String heading, String imgUrl, int backgroundDrawable) {
        this.title = title;
        this.heading = heading;
        this.imgUrl = imgUrl;
        this.backgroundDrawable = backgroundDrawable;
    }
  
    public int getBackgroundDrawable() {
        return backgroundDrawable;
    }
  
    public void setBackgroundDrawable(int backgroundDrawable) {
        this.backgroundDrawable = backgroundDrawable;
    }
}


Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class SliderAdapter extends PagerAdapter {
  
    // creating variables for layout 
    // inflater, context and array list.
    LayoutInflater layoutInflater;
    Context context;
    ArrayList sliderModalArrayList;
  
    // creating constructor.
    public SliderAdapter(Context context, ArrayList sliderModalArrayList) {
        this.context = context;
        this.sliderModalArrayList = sliderModalArrayList;
    }
  
    @Override
    public int getCount() {
        // inside get count method returning
        // the size of our array list.
        return sliderModalArrayList.size();
    }
      
    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        // inside isViewFrombject method we are 
        // returning our Relative layout object.
        return view == (RelativeLayout) object;
    }
  
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
          
        // in this method we will initialize all our layout 
        // items and inflate our layout file as well.
        layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
          
        // below line is use to inflate the 
        // layout file which we created.
        View view = layoutInflater.inflate(R.layout.slider_layout, container, false);
          
        // initializing our views.
        ImageView imageView = view.findViewById(R.id.idIV);
        TextView titleTV = view.findViewById(R.id.idTVtitle);
        TextView headingTV = view.findViewById(R.id.idTVheading);
        RelativeLayout sliderRL = view.findViewById(R.id.idRLSlider);
  
        // setting data to our views.
        SliderModal modal = sliderModalArrayList.get(position);
        titleTV.setText(modal.getTitle());
        headingTV.setText(modal.getHeading());
        Picasso.get().load(modal.getImgUrl()).into(imageView);
          
        // below line is to set background 
        // drawable to our each item
        sliderRL.setBackground(context.getResources().getDrawable(modal.getBackgroundDrawable()));
  
        // after setting the data to our views we 
        // are adding the view to our container.
        container.addView(view);
          
        // at last we are 
        // returning the view.
        return view;
    }
  
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        // this is a destroy view method 
        // which is use to remove a view.
        container.removeView((RelativeLayout) object);
    }
}


XML


    


XML


    


XML


    


Java
import android.os.Bundle;
import android.text.Html;
import android.widget.LinearLayout;
import android.widget.TextView;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for view pager, 
    // liner layout, adapter and our array list.
    private ViewPager viewPager;
    private LinearLayout dotsLL;
    SliderAdapter adapter;
    private ArrayList sliderModalArrayList;
    private TextView[] dots;
    int size;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing all our views.
        viewPager = findViewById(R.id.idViewPager);
        dotsLL = findViewById(R.id.idLLDots);
          
        // in below line we are creating a new array list.
        sliderModalArrayList = new ArrayList<>();
          
        // on below 3 lines we are adding data to our array list.
        sliderModalArrayList.add(new SliderModal("Slide 1 ", "Slide 1 heading", "https://images.unsplash.com/photo-1610842546881-b282c580b51d?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw5fHx8ZW58MHx8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60", R.drawable.gradient_one));
        sliderModalArrayList.add(new SliderModal("Slide 2 ", "Slide 2 heading", "https://images.unsplash.com/photo-1610783131813-475d08664ef6?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxMnx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60", R.drawable.gradient_two));
        sliderModalArrayList.add(new SliderModal("Slide 3 ", "Slide 3 heading", "https://images.unsplash.com/photo-1610832958506-aa56368176cf?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxN3x8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60", R.drawable.gradient_three));
  
        // below line is use to add our array list to adapter class.
        adapter = new SliderAdapter(MainActivity.this, sliderModalArrayList);
          
        // below line is use to set our
        // adapter to our viw pager.
        viewPager.setAdapter(adapter);
          
        // we are storing the size of our
        // array list in a variable.
        size = sliderModalArrayList.size();
          
        // calling method to add dots indicator
        addDots(size, 0);
          
        // below line is use to call on 
        // page change listener method.
        viewPager.addOnPageChangeListener(viewListner);
    }
  
    private void addDots(int size, int pos) {
        // inside this method we are
        // creating a new text view.
        dots = new TextView[size];
         
        // below line is use to remove all
        // the views from the linear layout.
        dotsLL.removeAllViews();
          
        // running a for loop to add 
        // number of dots to our slider.
        for (int i = 0; i < size; i++) {
            // below line is use to add the 
            // dots and modify its color.
            dots[i] = new TextView(this);
            dots[i].setText(Html.fromHtml("•"));
            dots[i].setTextSize(35);
              
            // below line is called when the dots are not selected.
            dots[i].setTextColor(getResources().getColor(R.color.black));
            dotsLL.addView(dots[i]);
        }
        if (dots.length > 0) {
            // this line is called when the dots 
            // inside linear layout are selected
            dots[pos].setTextColor(getResources().getColor(R.color.purple_200));
        }
    }
  
    // creating a method for view pager for on page change listener.
    ViewPager.OnPageChangeListener viewListner = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
  
        }
  
        @Override
        public void onPageSelected(int position) {
            // we are calling our dots method to 
            // change the position of selected dots.
            addDots(size, position);
        }
  
        @Override
        public void onPageScrollStateChanged(int state) {
  
        }
    };
}


步骤5:为我们的滑块项目创建布局文件

现在,我们将创建一个要显示在滑块中的项目。因此,要创建新的布局,请导航至应用程序> res>布局>右键单击它>单击New>布局资源文件,并将其命名为slider_layout ,并向其添加以下代码。

XML格式



  
    
    
  
    
    
  
    
    
  

步骤6:创建一个Modal类来存储Slider项的所有数据

要创建新的Modal类,请导航至应用程序> Java >应用程序的包名称>右键单击它,然后单击New> Java class并将其命名为SliderModal 。创建此类后,将以下代码添加到其中。

Java

public class SliderModal {
  
    // string variable for storing 
    // title, image url and description.
    private String title;
    private String heading;
    private String imgUrl;
    private int backgroundDrawable;
  
    public SliderModal() {
        // empty constructor is required
        // when using firebase
    }
  
    // creating getter methods.
    public String getTitle() {
        return title;
    }
  
    public void setTitle(String title) {
        this.title = title;
    }
  
    public String getHeading() {
        return heading;
    }
  
    // creating setter methods
    public void setHeading(String heading) {
        this.heading = heading;
    }
  
    public String getImgUrl() {
        return imgUrl;
    }
  
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
      
    // constructor for our modal class
    public SliderModal(String title, String heading, String imgUrl, int backgroundDrawable) {
        this.title = title;
        this.heading = heading;
        this.imgUrl = imgUrl;
        this.backgroundDrawable = backgroundDrawable;
    }
  
    public int getBackgroundDrawable() {
        return backgroundDrawable;
    }
  
    public void setBackgroundDrawable(int backgroundDrawable) {
        this.backgroundDrawable = backgroundDrawable;
    }
}

步骤7:创建一个Adapter类,用于将数据设置到每个视图

要创建新的Adapter类,请导航至应用程序> Java >应用程序的包名称>右键单击它> New Java类,并将其命名为SliderAdapter,然后将以下代码添加到其中。在代码内部添加了注释,以更详细地了解代码。

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class SliderAdapter extends PagerAdapter {
  
    // creating variables for layout 
    // inflater, context and array list.
    LayoutInflater layoutInflater;
    Context context;
    ArrayList sliderModalArrayList;
  
    // creating constructor.
    public SliderAdapter(Context context, ArrayList sliderModalArrayList) {
        this.context = context;
        this.sliderModalArrayList = sliderModalArrayList;
    }
  
    @Override
    public int getCount() {
        // inside get count method returning
        // the size of our array list.
        return sliderModalArrayList.size();
    }
      
    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        // inside isViewFrombject method we are 
        // returning our Relative layout object.
        return view == (RelativeLayout) object;
    }
  
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
          
        // in this method we will initialize all our layout 
        // items and inflate our layout file as well.
        layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
          
        // below line is use to inflate the 
        // layout file which we created.
        View view = layoutInflater.inflate(R.layout.slider_layout, container, false);
          
        // initializing our views.
        ImageView imageView = view.findViewById(R.id.idIV);
        TextView titleTV = view.findViewById(R.id.idTVtitle);
        TextView headingTV = view.findViewById(R.id.idTVheading);
        RelativeLayout sliderRL = view.findViewById(R.id.idRLSlider);
  
        // setting data to our views.
        SliderModal modal = sliderModalArrayList.get(position);
        titleTV.setText(modal.getTitle());
        headingTV.setText(modal.getHeading());
        Picasso.get().load(modal.getImgUrl()).into(imageView);
          
        // below line is to set background 
        // drawable to our each item
        sliderRL.setBackground(context.getResources().getDrawable(modal.getBackgroundDrawable()));
  
        // after setting the data to our views we 
        // are adding the view to our container.
        container.addView(view);
          
        // at last we are 
        // returning the view.
        return view;
    }
  
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        // this is a destroy view method 
        // which is use to remove a view.
        container.removeView((RelativeLayout) object);
    }
}

步骤8:为每张幻灯片的背景创建自定义渐变可绘制

导航到应用程序> res> drawable>右键单击它> New> drawable资源文件,并将文件命名为gradient_one,然后将以下代码添加到其中。

gradient_one.xml

XML格式



    

gradient_two.xml

XML格式



    

gradient_three.xml

XML格式



    

步骤9:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.text.Html;
import android.widget.LinearLayout;
import android.widget.TextView;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for view pager, 
    // liner layout, adapter and our array list.
    private ViewPager viewPager;
    private LinearLayout dotsLL;
    SliderAdapter adapter;
    private ArrayList sliderModalArrayList;
    private TextView[] dots;
    int size;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing all our views.
        viewPager = findViewById(R.id.idViewPager);
        dotsLL = findViewById(R.id.idLLDots);
          
        // in below line we are creating a new array list.
        sliderModalArrayList = new ArrayList<>();
          
        // on below 3 lines we are adding data to our array list.
        sliderModalArrayList.add(new SliderModal("Slide 1 ", "Slide 1 heading", "https://images.unsplash.com/photo-1610842546881-b282c580b51d?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw5fHx8ZW58MHx8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60", R.drawable.gradient_one));
        sliderModalArrayList.add(new SliderModal("Slide 2 ", "Slide 2 heading", "https://images.unsplash.com/photo-1610783131813-475d08664ef6?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxMnx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60", R.drawable.gradient_two));
        sliderModalArrayList.add(new SliderModal("Slide 3 ", "Slide 3 heading", "https://images.unsplash.com/photo-1610832958506-aa56368176cf?ixid=MXwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxN3x8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60", R.drawable.gradient_three));
  
        // below line is use to add our array list to adapter class.
        adapter = new SliderAdapter(MainActivity.this, sliderModalArrayList);
          
        // below line is use to set our
        // adapter to our viw pager.
        viewPager.setAdapter(adapter);
          
        // we are storing the size of our
        // array list in a variable.
        size = sliderModalArrayList.size();
          
        // calling method to add dots indicator
        addDots(size, 0);
          
        // below line is use to call on 
        // page change listener method.
        viewPager.addOnPageChangeListener(viewListner);
    }
  
    private void addDots(int size, int pos) {
        // inside this method we are
        // creating a new text view.
        dots = new TextView[size];
         
        // below line is use to remove all
        // the views from the linear layout.
        dotsLL.removeAllViews();
          
        // running a for loop to add 
        // number of dots to our slider.
        for (int i = 0; i < size; i++) {
            // below line is use to add the 
            // dots and modify its color.
            dots[i] = new TextView(this);
            dots[i].setText(Html.fromHtml("•"));
            dots[i].setTextSize(35);
              
            // below line is called when the dots are not selected.
            dots[i].setTextColor(getResources().getColor(R.color.black));
            dotsLL.addView(dots[i]);
        }
        if (dots.length > 0) {
            // this line is called when the dots 
            // inside linear layout are selected
            dots[pos].setTextColor(getResources().getColor(R.color.purple_200));
        }
    }
  
    // creating a method for view pager for on page change listener.
    ViewPager.OnPageChangeListener viewListner = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
  
        }
  
        @Override
        public void onPageSelected(int position) {
            // we are calling our dots method to 
            // change the position of selected dots.
            addDots(size, position);
        }
  
        @Override
        public void onPageScrollStateChanged(int state) {
  
        }
    };
}

现在运行您的应用程序,并查看该应用程序的输出。确保您的Internet保持打开状态。

输出:

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!