Tuesday, December 19, 2017

Image Slider Using ViewPager in android studio

Hey GuyZzz, This is Pooja , today iam going to show you haw to add View Pager on Fragment with Dot indicator, here in this example i tried many things so you guyz also can go with it .....



MainActivity.java



package android.prgguru.com.finalexampleoffragmentwithviewpager;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
Bundle savedInstanceState;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FirstFragment firstFragment= new FirstFragment();
        FragmentManager manager= getSupportFragmentManager();

        manager.beginTransaction()
                .replace(R.id.firstLayout,firstFragment,firstFragment.getTag())
                .commit();

        SecondFragment secondFragment= new SecondFragment();
        manager.beginTransaction()
                .replace(R.id.secondLayout,secondFragment,secondFragment.getTag())
                .commit();


    }


    //    @Override//    protected void onResume() {
//        super.onResume();//        if (allowRefresh)
//        {
//            allowRefresh = false;
//            lst_applist = db.load_apps();
//            getFragmentManager().beginTransaction().detach(this).attach(this).commit();
//        }////    }
    @Override    protected void onResume() {
            super.onResume();



    }
}









FirstFragment.java





package android.prgguru.com.finalexampleoffragmentwithviewpager;


import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.Timer;
import java.util.TimerTask;

import me.relex.circleindicator.CircleIndicator;


/** * A simple {@link Fragment} subclass. */public class FirstFragment extends Fragment {

    static int i=0;
   private Thread thread;
    Handler handler= new Handler();

    private int delay = 100; //milliseconds    private ViewPager viewPager;
    private int page = 0;
    private ViewPagerAdapter adapter;
    private static int currentpage = 0;
    private static int numpage = 0;

    Integer[] imageId = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};
    String[] imagesName = {"image1", "image2", "image3", "image4"};

    public FirstFragment() {
        // Required empty public constructor    }


    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
 {
        // Inflate the layout for this fragment       
 return inflater.inflate(R.layout.fragment_first, container, false);
    }

    @Override    public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
 {
        super.onViewCreated(view, savedInstanceState);
//        ViewPager viewPager=(ViewPager)view.findViewById(R.id.viewPager);
//        viewPager.setAdapter(new ViewPagerAdapter(getActivity()));

        viewPager = (ViewPager) view.findViewById(R.id.viewPager);
        adapter = new ViewPagerAdapter(getActivity(), imageId, imagesName);
        viewPager.setAdapter(adapter);
        //CircleIndicator <code>        CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.circleIndicator);
        indicator.setViewPager(viewPager);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override            public void onPageSelected(int i) {
                currentpage = i;
            }

            @Override            public void onPageScrollStateChanged(int i) {
            }
        });

        Runnable runnable = null;
        runnable = new Runnable() {
            @Override            public void run() {
                if (currentpage<adapter.getCount()-1){
                    viewPager.setCurrentItem(currentpage+1,true);
                }
                else{
                    viewPager.setCurrentItem(0,true);
                }
                new Handler().postDelayed(this,1000);
            }
        };
        new Handler().postDelayed(runnable,1000);


//final Handler handler= new Handler();//        Runnable runnable = new Runnable() {
//            @Override//            public void run() {

//                for (int i = 1; i < adapter.getCount(); i++) {
//                    final int value = i;//                    try {/
/                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();//                    }
//                    handler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            if(currentpage==numpage)
//                            {//                                currentpage=0;
//                                try {
//                                    Thread.sleep(1000);
//                                } catch (InterruptedException e) {
//                                    e.printStackTrace();
//                                }//                            }
////                            viewPager.setCurrentItem(value, true);
//                        }//                    });//                }
//            }//        };//        new Thread(runnable).start();
                         //Using Timer
//        final Handler handler = new Handler();
//        final Runnable update = new Runnable() {
//            @Override
//            public void run() {
//                if (currentpage == numpage) {
//                    currentpage = 0;////                }/
///                viewPager.setCurrentItem(currentpage++, true);
//            }//        };//        Timer swipe = new Timer();
//        swipe.schedule(new TimerTask() {
//            @Override//            public void run() {
//                handler.post(update);////            }
//        }, 1000, 1000);//        thread= new Thread(update);
//        thread.start();
        //ScroolImages using Thread




    }
public void show()
{
    for (int i = 0; i < adapter.getCount()-1; i++)
    {if (currentpage == numpage) {
                    currentpage = 0;

                }

                viewPager.setCurrentItem(currentpage++, true);

    }

}


//        private final Handler handler = new Handler();
//        void setImageMove()//        {
//            handler.post(ViewPagerVisibleScroll);
//        }//
//        Runnable ViewPagerVisibleScroll= new Runnable() {
//            @Override
//            public void run() {
////                if(i <= adapter.getCount()-1)
//                {
//                    viewPager.setCurrentItem(i, true);
//                    handler.postDelayed( ViewPagerVisibleScroll, 10000);
//                    i++;
////                }////            }//        };

    }


//    @Override
//    public void onStart() {
//        super.onStart();////    }
////    @Override//    public void onResume(){
//        super.onResume();
//        thread.run(); 
//threaded method for retrieving RS





//    @Override//    public void onBackPressed(){
//        if (getSupportFragmentManager().getBackStackEntryCount() == 1){
//            finish();//        }//        else {
//            super.onBackPressed();//        }//    }
////    @Override//    public void onResume() {//        super.onResume();
//        onViewCreated(getView(),);//    }



SecondFragment.java



package android.prgguru.com.finalexampleoffragmentwithviewpager;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;


/** * A simple {@link Fragment} subclass. */public class SecondFragment extends Fragment
 {

Button submit;
    TextView name;
    public SecondFragment() {
        // Required empty public constructor    }


    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment      
  return inflater.inflate(R.layout.fragment_second, container, false);


    }

    @Override    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        submit=(Button)view.findViewById(R.id.buttonSubmit);
        name=(TextView)view.findViewById(R.id.textName);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                String sname= name.getText().toString();
                Intent intent= new Intent(getActivity(),SecondActivity.class);
                getActivity().startActivity(intent);

            }
        });
    }
}



ViewPagerAdapter.java




package android.prgguru.com.finalexampleoffragmentwithviewpager;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/** * Created by Caless on 12/17/2017. */
public class ViewPagerAdapter extends PagerAdapter {

    private Activity activity;
    private Integer[] imagesArray;
    private String[] namesArray;
    Context mContext;
    LayoutInflater mLayoutInflater;
    int[] mResources = {
            R.drawable.image1,
            R.drawable.image2,
            R.drawable.image3,
            R.drawable.image4,
            R.drawable.image1,
            R.drawable.image4    };
    public ViewPagerAdapter(FragmentActivity activity, Integer[] imagesArray, String[] namesArray){

        this.activity = activity;
        this.imagesArray = imagesArray;
        this.namesArray = namesArray;
    }

//    public ViewPagerAdapter(Context context) {
//        mContext = context;
//        mLayoutInflater = (LayoutInflater) 
//mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);//    }
    @Override    public int getCount() {
        return imagesArray.length;
    }

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

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

        LayoutInflater inflater = ((Activity)activity).getLayoutInflater();

        View viewItem = inflater.inflate(R.layout.image_layout, container, false);
        ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);
        imageView.setImageResource(imagesArray[position]);
//        TextView textView1 = (TextView) viewItem.findViewById(R.id.textview);
//        textView1.setText(namesArray[position]);    
    ((ViewPager)container).addView(viewItem);

        return viewItem;
    }

    @Override    public void destroyItem(ViewGroup container, int position, Object object) 
{
        container.removeView((LinearLayout) object);
    }
}



SecondActivity.java




package android.prgguru.com.finalexampleoffragmentwithviewpager;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SecondActivity extends AppCompatActivity {

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



activity_main.xml




<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:app="http://schemas.android.com/apk/res-auto"    
xmlns:tools="http://schemas.android.com/tools"    
android:layout_width="match_parent"    
android:layout_height="match_parent"   
 tools:context="android.prgguru.com.finalexampleoffragmentwithviewpager.MainActivity">

    <android.support.constraint.ConstraintLayout       
 android:id="@+id/firstLayout"      
 android:layout_width="match_parent"       
 android:layout_height="200dp"
 app:layout_constraintHorizontal_bias="1.0"   
 app:layout_constraintLeft_toLeftOf="parent"        
 app:layout_constraintRight_toRightOf="parent"       
 app:layout_constraintTop_toTopOf="parent"        
 tools:layout_constraintLeft_creator="1"        
 tools:layout_constraintRight_creator="1"        
 tools:layout_constraintTop_creator="1">
</android.support.constraint.ConstraintLayout>

    <RelativeLayout       
  android:id="@+id/secondLayout"      
  android:layout_width="0dp"      
  android:layout_height="0dp"      
  android:layout_marginBottom="11dp"       
  android:layout_marginEnd="8dp"       
  android:layout_marginStart="8dp"       
  app:layout_constraintBottom_toBottomOf="parent"      
  app:layout_constraintLeft_toLeftOf="parent"       
  app:layout_constraintRight_toRightOf="parent"        
  app:layout_constraintTop_toBottomOf="@+id/firstLayout"        
  tools:layout_constraintBottom_creator="1"       
  tools:layout_constraintLeft_creator="1"       
  tools:layout_constraintRight_creator="1"       
  tools:layout_constraintTop_creator="1"       
  android:layout_marginLeft="8dp"      
  app:layout_constraintVertical_bias="0.0">
    </RelativeLayout>

</android.support.constraint.ConstraintLayout>




activity_second.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto"   
xmlns:tools="http://schemas.android.com/tools"   
android:layout_width="match_parent"   
android:layout_height="match_parent"   
tools:context="android.prgguru.com.finalexampleoffragmentwithviewpager.SecondActivity">
</android.support.constraint.ConstraintLayout>


fragment_first.xml



<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"    
xmlns:app="http://schemas.android.com/apk/res-auto"  
tools:context="android.prgguru.com.finalexampleoffragmentwithviewpager.FirstFragment">

    <!-- TODO: Update blank fragment layout -->  
 <android.support.v4.view.ViewPager     
 android:layout_width="match_parent"       
 android:layout_height="match_parent"      
 android:id="@+id/viewPager"       >
</android.support.v4.view.ViewPager>
    <me.relex.circleindicator.CircleIndicator     
   android:layout_width="match_parent"        
   android:layout_height="30dp"        
   android:id="@+id/circleIndicator"
        android:layout_alignBottom="@+id/viewPager"       
    android:foreground="@color/colorPrimary">
</me.relex.circleindicator.CircleIndicator>

</RelativeLayout>


fragemnt_second.xml




<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="android.prgguru.com.finalexampleoffragmentwithviewpager.SecondFragment">

    <!-- TODO: Update blank fragment layout -->  
  <TextView
        android:layout_width="wrap_content"       
        android:layout_height="wrap_content"   
        android:text="Register Here"      
        android:textSize="30dp"        
        android:id="@+id/textView"  
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"        
        android:id="@+id/textName"       
        android:textSize="20dp"      
        android:text="Name"        
        android:layout_marginTop="144dp"     
        android:layout_below="@+id/textView"       
        android:layout_alignParentStart="true"        
        android:layout_marginStart="24dp" />
    <EditText        
        android:layout_width="wrap_content"   
        android:layout_height="wrap_content"     
        android:id="@+id/editName"       
        android:textSize="20dp"      
        android:hint="Enter Your Name Here"     
        android:layout_marginEnd="38dp"       
        android:layout_alignBaseline="@+id/textName"   
        android:layout_alignBottom="@+id/textName"       
        android:layout_alignParentEnd="true" />
    <Button        
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"      
        android:id="@+id/buttonSubmit"      
        android:layout_below="@+id/editName"   
        android:layout_alignEnd="@+id/editName"     
        android:layout_marginTop="67dp"       
        android:text="submit"/>



</RelativeLayout>



image_layout.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"    
android:orientation="vertical" android:layout_width="match_parent"    
android:layout_height="match_parent">
    <RelativeLayout        
android:layout_width="match_parent"        
android:layout_height="match_parent">
     <ImageView            
android:id="@+id/imageView"            
android:layout_width="match_parent"            
android:layout_height="match_parent"            
android:scaleType="centerCrop"            
android:layout_alignParentTop="true"            
android:layout_alignParentStart="true" />
        <TextView            
android:layout_width="match_parent"           
 android:layout_height="wrap_content"            
android:id="@+id/textview"/>
    </RelativeLayout>
</LinearLayout>



Manifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"    
package="android.prgguru.com.finalexampleoffragmentwithviewpager">

    <application        android:allowBackup="true"        
android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"       
 android:roundIcon="@mipmap/ic_launcher_round"        
android:supportsRtl="true"  
      android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity"></activity>
    </application>

</manifest>


buile.gradle(app)


compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:support-v4:26.+'
compile 'me.relex:circleindicator:1.2.2@aar'

Tuesday, September 26, 2017