简体   繁体   English

使用ViewPager Android单击按钮时幻灯片的幻灯片更改

[英]Slide Changes in slideshow when a button is clicked using viewpager android

I have a slideshow which is initiated in between the app like after first two activities are done , then slideshow takes place. 我有一个幻灯片放映,它是在应用之间启动的,例如在完成前两个活动之后,然后进行幻灯片放映。 So, I want to change the slide when an image is clicked or tapped. 因此,我想在单击或点击图像时更改幻灯片。 Codes are provided here : slidescreen.java 此处提供代码:slidescreen.java

package com.dekton.dektonapp;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

public class slidescreen extends ActionBarActivity {

//Declare variables
ViewPager viewPager;
PagerAdapter adapter;
int[] background;
int[] icon;
String[] title;
String[] title_2;
String[] description;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.slidescreenmain);

    //Generate sample data
    background = new int[]{R.mipmap.bg1, R.mipmap.bg2, R.mipmap.bg3, R.mipmap.bg4, R.mipmap.bg5, R.mipmap.bg6,
            R.mipmap.bg7, R.mipmap.bg8, R.mipmap.bg9, R.mipmap.bg10, R.mipmap.bg11, R.mipmap.bg12};

    icon = new int[]{R.mipmap.im1, R.mipmap.im2, R.mipmap.im3, R.mipmap.im4, R.mipmap.im5,
            R.mipmap.im6, R.mipmap.im7, R.mipmap.im8, R.mipmap.im9, R.mipmap.im10, R.mipmap.im11, R.mipmap.im12};

    title = new String[]{"ALTA RESISTENCIA A", "ALTA RESISTENCIA", "ALTAMENTE", "RESISTENCIA A", "MATERIAL", "ALTA RESISTENCIA",
            "RESISTENCIA AL", "RESISTENCIA", "ESTABILIDAD", "ESTABILIDAD", "RESISTENCIA A", "NULA ABSORCIÓN"};

    title_2 = new String[]{"LOS RAYOS UV", "AL FUEGO Y AL CALOR", "RESISTENTE AL RAYADO", "LAS MANCHAS", "INCOMBUSTIBLE", "A LA HIDRÓLISIS",
            "HIELO Y DESHIELO", "MECÁNICA", "DIMENSIONAL", "DEL COLOR", "LA ABRASIÓN", "DEL AGUA"};

    description = new String[]{"Dekton es altamente resistente a\n" + "los rayos ultravioleta (UV) y su color\n" +
            "no degrada con el tiempo, lo que\n" + "hace que sea un material perfecto\n" + "tanto para interiores como para\n" +
            "exteriores.",
            "Dekton presenta una muy buena\n" + "resistencia a las altas temperaturas sin\n" + "que se vea afectada su estética ni su\n" +
                    "propiedades. Los utensilios calientes,\n" + "electrodomésticos, ollas y sartenes, se\n" + "pueden colocar directamente sobre la\n" +
                    "superficie sin peligro ni daño alguno.",
            "Dekton es una superficie con alta\n" + "resistencia al rayado. No se raya\n" + "con los utensilios de uso doméstico.\n" +
                    "No obstante, recomendamos el uso\n" + "de tablas de corte para asi proteger\n" + "los utensilios domésticos.",
            "Debido a su baja porosidad, la nueva\n" + "superficie Dekton, es una superficie\n" + "altamente resistente , tanto a las manchas\n" +
                    "ocasionales en el uso domestico como a\n" + "los agentes químicos. Incluso las manchas\n" + "más difíciles como las de vino, café, tinta y\n" +
                    "óxido se pueden limpiar fácilmente. Las\n" + "salpicaduras o gotas de productos de\n" + "limpieza cotidianos como lejía, limpia\n" +
                    "tuberías o desengrasantes para hornos no\n" + "producen daño alguno al material.",
            "Text Text Text Text Text Text Text Text Text\n" + "Text Text Text Text Text Text Text Text Text\n" +
                    "Text Text Text Text Text Text Text Text Text\n" + "Text Text Text Text Text Text Text Text Text\n" +
                    "Text Text Text Text Text Text Text Text Text\n" + "Text Text Text Text Text Text Text Text Text\n" +
                    "Text Text Text Text Text Text Text",
            "Text Text Text Text Text Text Text Text\n" + "Text Text Text Text Text Text Text Text\n" +
                    "Text Text Text Text Text Text Text Text\n" + "Text Text Text Text Text Text Text Text\n" +
                    "Text Text Text Text Text Text Text Text\n" + "Text Text Text Text Text Text Text",
            "El bajo coeficiente de expansión térmico\n" + "de Dekton hace que sea resistente al\n" +
                    "choque térmico, del paso del calor al frío\n" + "extremo. Su resistencia natural al hielo y al\n" +
                    "deshielo hacen que sea un material\n" + "perfecto incluso en los entornos más fríos\n" + "y extremos.",
            "Con una resistencia a la flexión 3 veces\n" + "mayor de la que ofrece el granito, Dekton\n" +
                    "puede instalarse en espesores mas finos,\n" + "permitiendo un voladizo sin soporte de\n" +
                    "hasta 30cm en encimeras, islas y barras\n" + "de bar (dependiendo del espesor).",
            "Dekton es un material donde se controla\n" + "de forma exhaustiva tanto la dimensión\n" +
                    "como el grosor en toda la tabla, lo cual\n" + "reduce la necesidad de correcciones sobre\n" +
                    "la superficie y facilita asi su instalación.",
            "El proceso de fabricación de Dekton nos\n" + "permite controlar la pigmentación y la\n" +
                    "estética del material, dotándolo de una\n" + "mejor consistencia del color en todas las\n" +
                    "tablas. El resultado es un producto que no\n" + "decolora con el tiempo. Una vez instalada,\n" +
                    "la superficie mantendrá su aspecto\n" + "durante toda la vida útil del producto.",
            "Dekton es incluso más resistente a la\n" + "abrasión que el granito, lo cual lo convierte\n" +
                    "en la superficie ideal para aplicaciones\n" + "comerciales y áreas de alto tránsito como\n" +
                    "solerías y fachadas. Mientras que otras\n" + "superficies muestran desgaste con el paso\n" +
                    "del tiempo, el acabado de Dekton\n" + "perdurará durante toda la vida del\n" +
                    "producto y no necesitará ser reemplazado\n" + "o retocado en ningún momento.",
            "Dekton es un material no poroso y no\n" + "necesita ser sellado en ningún momento.\n" +
                    "Por naturaleza, es capaz del repeler\n" + "líquidos y gases para que no penetren en\n" +
                    "la superficie. De este modo, el\n" + "mantenimiento de la superficie es mínimo\n" +
                    "y más fácil de limpiar."};
    // Locate the ViewPager in viewpager_main.xml
    viewPager = (ViewPager) findViewById(R.id.pager);
    // Pass results to ViewPagerAdapter Class
    adapter = new ViewPagerAdapter(slidescreen.this, background, icon, title, title_2, description);
    // Binds the Adapter to the ViewPager
    viewPager.setAdapter(adapter);

    getSupportActionBar().hide();
}


public void onClickSlideDown(View view) {

}

public void onClickCloseButton(View view) {
    Intent i = new Intent(this, glass_3.class);
    startActivity(i);
}
}

ViewPagerAdapter.java ViewPagerAdapter.java

package com.dekton.dektonapp;

import android.content.Context;
import android.graphics.Typeface;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ViewPagerAdapter extends PagerAdapter implements Animation.AnimationListener {

//Declare variables
Context context;
int[] background;
int[] icon;
String[] title;
String[] title_2;
String[] description;
LayoutInflater inflater;

public ViewPagerAdapter(Context context, int[] background, int[] icon, String[] title, String[] title_2, String[] description) {
    this.context = context;
    this.background = background;
    this.icon = icon;
    this.title = title;
    this.title_2 = title_2;
    this.description = description;
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((RelativeLayout) object);
}

@Override
public int getCount() {
    return background.length;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {

    //Declare variables
    ImageView iconimage, whitebox, bgimage;
    TextView titletext, title_2text, descriptiontext;
    Animation translate, slide;
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = inflater.inflate(R.layout.slidescreen_item, container, false);

    //Locate textviews in slidescreen_item.xml
    titletext = (TextView) itemView.findViewById(R.id.title);
    title_2text = (TextView) itemView.findViewById(R.id.title_2);
    descriptiontext = (TextView) itemView.findViewById(R.id.description);

    //Capture position and set to textviews
    titletext.setText(this.title[position]);
    title_2text.setText(this.title_2[position]);
    descriptiontext.setText(this.description[position]);

    //Locate imageview in slidescreen_item.xml
    iconimage = (ImageView) itemView.findViewById(R.id.icon);
    whitebox = (ImageView) itemView.findViewById(R.id.whitebox);
    bgimage = (ImageView) itemView.findViewById(R.id.bgimage);

    //Capture position and set to the Imageview
    bgimage.setBackgroundResource(this.background[position]);
    iconimage.setImageResource(this.icon[position]);
    //Apply font
    Typeface BryantProBold = Typeface.createFromAsset(this.context.getAssets(), "BryantProBold.otf");
    Typeface PFHighwaySansProRegular = Typeface.createFromAsset(this.context.getAssets(), "PFHighwaySansProRegular.ttf");
    titletext.setTypeface(PFHighwaySansProRegular);
    title_2text.setTypeface(PFHighwaySansProRegular);
    descriptiontext.setTypeface(BryantProBold);

    //Apply animations
    translate = new TranslateAnimation(TranslateAnimation.ABSOLUTE, 0f, TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.ABSOLUTE, -48f, TranslateAnimation.ABSOLUTE, 150f);
    translate.setDuration(5000);
    translate.setRepeatCount(-1);
    translate.setRepeatMode(Animation.REVERSE);
    translate.setInterpolator(new LinearInterpolator());
    bgimage.setAnimation(translate);
    slide = AnimationUtils.loadAnimation(this.context, R.anim.whiteboxanim);
    slide.setAnimationListener(this);
    whitebox.startAnimation(slide);
    iconimage.startAnimation(slide);
    titletext.startAnimation(slide);
    title_2text.startAnimation(slide);
    descriptiontext.startAnimation(slide);

    ((ViewPager)container).addView(itemView);

    return itemView;
}


@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    //Remove slidescreen_item.xml from viewpager
    ((ViewPager) container).removeView((RelativeLayout) object);
}

@Override
public void onAnimationStart(Animation animation) {

}

@Override
public void onAnimationEnd(Animation animation) {

}

@Override
public void onAnimationRepeat(Animation animation) {

}
}

In the ViewPagerAdapter code i have to make change such that slide changes when an image that is present in layout is clicked and i have disabled the default swipe action of viewpager. 在ViewPagerAdapter代码中,我必须进行更改,以便在单击布局中存在的图像并且我已禁用viewpager的默认滑动操作时更改幻灯片。 Thanks in advance :) 提前致谢 :)

I think you need this setCurrentItem(int, boolean) 我认为您需要此setCurrentItem(int,boolean)

This method change current displayed item. 此方法更改当前显示的项目。 You can use also second parameter if you need a smooth scrolling to item. 如果需要平滑滚动到项目,也可以使用第二个参数。

Actually you code will be looks : 实际上,您的代码将如下所示:

viewPager.setOnClickListener(new OnClickListener() {
      @Override
      public void OnClick(View view) {
          int current = viewPager.getCurrentItem() + 1;
          if(current<viewPager.getChildCount()){
              viewPager.setCurrentItem(current);
          } else {
              viewPager.setCurrentItem(0);
          }
      }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM