📌  相关文章
📜  如何使用Firebase在Android中创建动态自动图像滑块?

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

我们已经看到许多应用程序以滑块格式显示图像,而横幅广告会自动滑动。在许多电子商务网站中都可以看到“自动图像”滑块的这种功能。在许多包含图像的应用程序中都可以看到此功能。在本文中,我们将介绍如何在Android中创建动态的Auto Image Slider 。因此,我们将使用Firebase使用Firebase将图像加载到滑块内。借助Firebase,可以实时更新这些图像,而无需更新应用程序。对于SliderView的实现,我们将使用SliderView库。

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

我们将创建一个简单的应用程序,在其中创建滑块视图,并在SliderView内显示Firebase的图像。下面给出了一个示例GIF,以了解我们将在本文中做些什么。注意,我们将使用Java语言实现该项目。

具有Firebase示例GIF的Android中的动态自动图像滑块

分步实施

步骤1:创建一个新项目

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

第2步:将您的应用连接到Firebase

创建新项目后,导航至顶部栏上的“工具”选项。在里面单击Firebase。单击Firebase后,您可以在屏幕快照中看到下面提到的右列。

在该列内,导航到Firebase Cloud Firestore。单击该选项,您将在“将应用程序连接到Firebase”和“将Cloud Firestore添加到您的应用程序”中看到两个选项。单击立即连接选项,您的应用程序将连接到Firebase。之后,单击第二个选项,现在您的应用已连接到Firebase。将您的应用程序连接到Firebase后,您将看到以下屏幕。

之后,确认已将Firebase Firestore数据库的依赖项添加到我们的Gradle文件中。导航到该文件中的app> Gradle脚本,以检查是否添加了以下依赖项。如果您的build.gradle文件中不存在以下依赖项。在“依赖项”部分中添加以下依赖项。

添加此依赖关系后,我们将为SliderView和Picasso添加依赖关系,这些依赖关系将用于从其图像URL加载图像。

添加这些依赖项后,同步您的项目。现在,我们将转到应用程序的AndroidManifest.xml部分。

步骤3:使用AndroidManifest.xml文件

要将数据添加到Firebase,我们必须授予访问Internet的权限。要添加这些权限,请导航至应用程序> AndroidManifest.xml,然后在该文件内向其添加以下权限。

XML



XML


  
    
    
  


Java
public class SliderData {
  
    // string for our image url.
    private String imgUrl;
  
    // empty constructor which is
    // required when using Firebase.
    public SliderData() {
    }
  
    // Constructor
    public SliderData(String imgUrl) {
        this.imgUrl = imgUrl;
    }
  
    // Getter method.
    public String getImgUrl() {
        return imgUrl;
    }
  
    // Setter method.
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
}


XML


  
    
    
  


Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
  
import com.smarteist.autoimageslider.SliderViewAdapter;
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
import java.util.List;
  
public class SliderAdapter extends SliderViewAdapter {
      
    // creating a variable for 
    // context and array list.
    private Context context;
    private List mSliderItems = new ArrayList<>();
  
    // constructor for our adapter class.
    public SliderAdapter(Context context, List mSliderItems) {
        this.context = context;
        this.mSliderItems = mSliderItems;
    }
  
    @Override
    public SliderAdapterVH onCreateViewHolder(ViewGroup parent) {
        // inside the on Create view holder method we are 
        // inflating our layout file which we have created.
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_slider_item, null);
        return new SliderAdapterVH(inflate);
    }
  
    @Override
    public void onBindViewHolder(SliderAdapterVH viewHolder, int position) {
        // inside on bind view holder method we are 
        // getting url of image from our modal class
        // and setting that url for image inside our 
        // image view using Picasso.
        final SliderData sliderItem = mSliderItems.get(position);
        Picasso.get().load(sliderItem.getImgUrl()).into(viewHolder.imageView);
    }
  
    @Override
    public int getCount() {
        // returning the size of our array list.
        return mSliderItems.size();
    }
  
    // view holder class for initializing our view holder.
    class SliderAdapterVH extends SliderViewAdapter.ViewHolder {
  
        // variables for our view and image view.
        View itemView;
        ImageView imageView;
  
        public SliderAdapterVH(View itemView) {
            super(itemView);
            // initializing our views.
            imageView = itemView.findViewById(R.id.idIVimage);
            this.itemView = itemView;
        }
    }
}


Java
import android.os.Bundle;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
  
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.smarteist.autoimageslider.SliderAnimations;
import com.smarteist.autoimageslider.SliderView;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our adapter, array list, 
    // firebase firestore and our sliderview.
    private SliderAdapter adapter;
    private ArrayList sliderDataArrayList;
    FirebaseFirestore db;
    private SliderView sliderView;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // creating a new array list fr our array list.
        sliderDataArrayList = new ArrayList<>();
          
        // initializing our slider view and
        // firebase firestore instance.
        sliderView = findViewById(R.id.slider);
        db = FirebaseFirestore.getInstance();
          
        // calling our method to load images.
        loadImages();
    }
  
    private void loadImages() {
        // getting data from our collection and after 
        // that calling a method for on success listener.
        db.collection("Slider").get().addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                  
                // inside the on success method we are running a for loop
                // and we are getting the data from Firebase Firestore
                for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
                      
                    // after we get the data we are passing inside our object class.
                    SliderData sliderData = documentSnapshot.toObject(SliderData.class);
                    SliderData model = new SliderData();
                      
                    // below line is use for setting our
                    // image url for our modal class.
                    model.setImgUrl(sliderData.getImgUrl());
                      
                    // after that we are adding that 
                    // data inside our array list.
                    sliderDataArrayList.add(model);
                      
                    // after adding data to our array list we are passing 
                    // that array list inside our adapter class.
                    adapter = new SliderAdapter(MainActivity.this, sliderDataArrayList);
                      
                    // belows line is for setting adapter
                    // to our slider view
                    sliderView.setSliderAdapter(adapter);
                      
                    // below line is for setting animation to our slider.
                    sliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
                      
                    // below line is for setting auto cycle duration.
                    sliderView.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH);
                      
                    // below line is for setting 
                    // scroll time animation
                    sliderView.setScrollTimeInSec(3);
                      
                    // below line is for setting auto
                    // cycle animation to our slider
                    sliderView.setAutoCycle(true);
                      
                    // below line is use to start 
                    // the animation of our slider view.
                    sliderView.startAutoCycle();
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // if we get any error from Firebase we are 
                // displaying a toast message for failure
                Toast.makeText(MainActivity.this, "Fail to load slider data..", Toast.LENGTH_SHORT).show();
            }
        });
    }
}


步骤4:使用activity_main.xml文件

转到activity_main.xml文件,并参考以下代码。以下是activity_main.xml文件的代码。

XML格式



  
    
    
  

第5步:创建模态类以在Slider中存储图像的URL

现在,我们将创建一个模式类,用于存储图像的URL。用于创建新的Java类。导航至应用程序> Java >您的应用程序的包名称,然后右键单击它,然后单击新建> Java类。给您的Java类命名,并在其中添加以下代码。在这里,我们将其命名为SliderData 。下面是SliderData的代码。 Java文件。

Java

public class SliderData {
  
    // string for our image url.
    private String imgUrl;
  
    // empty constructor which is
    // required when using Firebase.
    public SliderData() {
    }
  
    // Constructor
    public SliderData(String imgUrl) {
        this.imgUrl = imgUrl;
    }
  
    // Getter method.
    public String getImgUrl() {
        return imgUrl;
    }
  
    // Setter method.
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
}

第6步:在SliderView中为我们的商品创建一个布局文件

要创建一个新的布局文件以显示在我们的SliderView中,请导航至应用程序> res>布局>右键单击它,然后单击“新建”>“布局资源文件”,然后为文件命名。在这里,我们将文件名为image_slider_item并添加以下代码。

XML格式



  
    
    
  

第7步:创建一个Adapter类以在Slider项中设置数据

要创建适配器类,请导航至应用程序> Java >应用程序的包名称>右键单击它>新建> Java类,并将您的类命名为SliderAdapter并在其中添加以下代码。

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
  
import com.smarteist.autoimageslider.SliderViewAdapter;
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
import java.util.List;
  
public class SliderAdapter extends SliderViewAdapter {
      
    // creating a variable for 
    // context and array list.
    private Context context;
    private List mSliderItems = new ArrayList<>();
  
    // constructor for our adapter class.
    public SliderAdapter(Context context, List mSliderItems) {
        this.context = context;
        this.mSliderItems = mSliderItems;
    }
  
    @Override
    public SliderAdapterVH onCreateViewHolder(ViewGroup parent) {
        // inside the on Create view holder method we are 
        // inflating our layout file which we have created.
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_slider_item, null);
        return new SliderAdapterVH(inflate);
    }
  
    @Override
    public void onBindViewHolder(SliderAdapterVH viewHolder, int position) {
        // inside on bind view holder method we are 
        // getting url of image from our modal class
        // and setting that url for image inside our 
        // image view using Picasso.
        final SliderData sliderItem = mSliderItems.get(position);
        Picasso.get().load(sliderItem.getImgUrl()).into(viewHolder.imageView);
    }
  
    @Override
    public int getCount() {
        // returning the size of our array list.
        return mSliderItems.size();
    }
  
    // view holder class for initializing our view holder.
    class SliderAdapterVH extends SliderViewAdapter.ViewHolder {
  
        // variables for our view and image view.
        View itemView;
        ImageView imageView;
  
        public SliderAdapterVH(View itemView) {
            super(itemView);
            // initializing our views.
            imageView = itemView.findViewById(R.id.idIVimage);
            this.itemView = itemView;
        }
    }
}

步骤8:使用MainActivity。 Java文件

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

Java

import android.os.Bundle;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
  
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.smarteist.autoimageslider.SliderAnimations;
import com.smarteist.autoimageslider.SliderView;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our adapter, array list, 
    // firebase firestore and our sliderview.
    private SliderAdapter adapter;
    private ArrayList sliderDataArrayList;
    FirebaseFirestore db;
    private SliderView sliderView;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // creating a new array list fr our array list.
        sliderDataArrayList = new ArrayList<>();
          
        // initializing our slider view and
        // firebase firestore instance.
        sliderView = findViewById(R.id.slider);
        db = FirebaseFirestore.getInstance();
          
        // calling our method to load images.
        loadImages();
    }
  
    private void loadImages() {
        // getting data from our collection and after 
        // that calling a method for on success listener.
        db.collection("Slider").get().addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                  
                // inside the on success method we are running a for loop
                // and we are getting the data from Firebase Firestore
                for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
                      
                    // after we get the data we are passing inside our object class.
                    SliderData sliderData = documentSnapshot.toObject(SliderData.class);
                    SliderData model = new SliderData();
                      
                    // below line is use for setting our
                    // image url for our modal class.
                    model.setImgUrl(sliderData.getImgUrl());
                      
                    // after that we are adding that 
                    // data inside our array list.
                    sliderDataArrayList.add(model);
                      
                    // after adding data to our array list we are passing 
                    // that array list inside our adapter class.
                    adapter = new SliderAdapter(MainActivity.this, sliderDataArrayList);
                      
                    // belows line is for setting adapter
                    // to our slider view
                    sliderView.setSliderAdapter(adapter);
                      
                    // below line is for setting animation to our slider.
                    sliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
                      
                    // below line is for setting auto cycle duration.
                    sliderView.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH);
                      
                    // below line is for setting 
                    // scroll time animation
                    sliderView.setScrollTimeInSec(3);
                      
                    // below line is for setting auto
                    // cycle animation to our slider
                    sliderView.setAutoCycle(true);
                      
                    // below line is use to start 
                    // the animation of our slider view.
                    sliderView.startAutoCycle();
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // if we get any error from Firebase we are 
                // displaying a toast message for failure
                Toast.makeText(MainActivity.this, "Fail to load slider data..", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

第9步:将数据添加到Firebase Firestore控制台

转到Firebase,然后单击右上角的“转到控制台”选项。

单击此屏幕后,您将看到下面的屏幕,其中包含您选择的项目的所有项目。

在该屏幕内,单击左侧窗口中的n Firebase Firestore数据库。

单击创建数据库选项后,您将看到以下屏幕。

在此屏幕内,我们必须选择“以测试模式启动”选项。我们正在使用测试模式,因为我们未在应用内设置身份验证。因此,我们选择在测试模式下启动。选择测试模式后,单击下一步选项,您将看到以下屏幕。

在此屏幕内,我们只需单击“启用”按钮即可启用我们的Firebase Firestore数据库。完成此过程后,我们只需要在Firebase Firestore控制台内添加数据,即可将图像添加到滑块。要添加数据,请单击开始收集选项,您将看到以下屏幕。

添加此数据后,单击“下一步”选项,您将看到以下屏幕。

将数据添加到我们的Firebase Firestore控制台中,然后单击“保存”。您的第一张图像已添加到滑块中。同样,通过单击“添加文档”按钮添加更多图像。

添加这些图像后,运行您的应用程序,您将在以下屏幕上看到输出。

输出:

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