Skip to main content

Swipe To Change Page in ANDROID or Page Swiping Using ViewPager FragmentActivity in ANDROID

See more basics on Android along with interview questions

Here we are going to deal with horizontal view swiping with ViewPager.The ViewPager control (android.support.v4.view.ViewPager) provides the horizontal swiping behavior. It can be used within your layouts much like a Gallery or other adapter-populated user interface control would be. The PagerAdapter (android.support.v4.view.PagerAdapter) class is used to define the data displayed by the ViewPager control. Here we are going to load a string from json(kept in text file in asset folder) in the swiping view.
Here we go with java source code
 
public class Viewpagers extends FragmentActivity {

 // android.support.v4.app.FragmentStatePagerAdapter.
    SectionsPagerAdapter mSectionsPagerAdapter;
 // The ViewPager that will host the section contents.
    ViewPager mViewPager;

 String text;
 JSONArray jArray;
 ArrayList<String> Questionarray = new ArrayList<String>();
 ArrayList<String> Answerarray = new ArrayList<String>();

       @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  setContentView(R.layout.pageswipe);
  // ================read asset =========================
  InputStream stream;
    try {
       stream = getAssets().open("questions.txt");
       int size = stream.available();
       byte[] buffer = new byte[size];
       stream.read(buffer);
       stream.close();
   text = new String(buffer);//get jason as string from file
  } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
  }
  parseJason(text);
  // ===============page viewer ==========================
    mSectionsPagerAdapter = new SectionsPagerAdapter(this,
    getSupportFragmentManager());
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
       }
                // ============== parse jason ======================
             private void parseJason(String text) {
  String parser = text;
  try {
      jArray = new JSONArray(text);
      for (int i = 0; i < jArray.length(); i++) {
      JSONObject json_data = jArray.getJSONObject(i);
      Questionarray.add(json_data.getString("ques"));
      Answerarray.add(json_data.getString("ans"));
   }
  } catch (JSONException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
  }
       }
               // ===================== adapter =======================
   public class SectionsPagerAdapter extends FragmentPagerAdapter {
       Context c;
   public SectionsPagerAdapter(Context c, FragmentManager fm) {
       super(fm);
       this.c = c;
  }
  @Override
  public Fragment getItem(int i) {

     Fragment fragment = null;
     String ques = Questionarray.get(i);
     String ans = Answerarray.get(i);

     fragment = new Page1(c, ques, ans);//pass value to be displayed in inflated view
     return fragment;
  }
  @Override
  public int getCount() {
      return Questionarray.size();//get number of pages to be displayed
  }
  @Override
  public CharSequence getPageTitle(int position) {
      String s = "Page  "+position;//setting the title
      return s;
  }
       }   }

in pageswipe.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relative"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

        <!--
    This title strip will display the currently visible page title, as well as the page
    titles for adjacent pages.
        -->

        <android.support.v4.view.PagerTitleStrip
            android:id="@+id/pager_title_strip"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="#33b5e5"
            android:paddingBottom="5dp"
            android:paddingTop="5dp"
            android:textColor="#fff" />
    </android.support.v4.view.ViewPager>

</RelativeLayout>
Create a new java class from where you can inflate the view foe viewpager..
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class Page1 extends Fragment {
  Context c2;
  String ques, ans;
 public Page1() {
   }
 public Page1(Context c2, String ques, String ans) {
    this.c2 = c2;
    this.ques = ques;
    this.ans = ans;
 }
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
      View v = inflater.inflate(R.layout.sections, null);  //inflate view
  try {
      TextView questext = (TextView) v.findViewById(R.id.textView1);
      questext.setText(ques);  //added to textview
  } catch (Exception e) {
      System.out.println("Exception......");
  }
  return v;
 }
}
inflated xml : sections.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linear"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />
   
</LinearLayout>
 

Comments

  1. Thanks for this post,it was really helpful..

    ReplyDelete
  2. This is a nice post. keep on posting like this.

    ReplyDelete

Post a Comment

Popular posts from this blog

Getting started with IBM worklight Mobile App In Eclipse using Ionic / Angularjs

Install Eclipse and add IBM MobileFirst Platform Studio 7.1.0 .  You can follow the following steps : Goto Help > > Eclipse Market Place >> and search for IBM MobileFirst Platform Studio 7.1.0 . and u can add and install thet plugin and get started with ionic - angular app development. You can start the new project and so can add your Environment needed and start development. After creating the sample project you can add ionic bundle folder inside your application so that you get all the necessary features of ionic development. Details and other way of installation is explained here  

Spannable String in Android - URL Span ,Clickable Span, Rich-Style Formatting of Textview .....

See more Android Tutorials here....... Faster Loading images in GridViews or ListViews Spannable brings lots of possibility to TextView, includes displaying various appearance of a Text and onClick callbak. The SpannableString class allows you to easily format certain pieces which are called spans of a string, by applying CharacterStyle ie,color, font, ormake it a link . Here is an example where, explained how to use spannable string to give font size, color, linking a text via clickable span and through URL Span and to strike through the text. Lets go through the example : import android.os.Bundle; import android.text.SpannableString; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.text.style.RelativeSizeSpan; import android.text.style.StrikethroughSpan; import android.text.style.URLSpan; import android.view.View; import android.widget.TextView; import android.widget.Toast; ...

Calling a script from an external file

We Can just recall the previous example of image switching to understand how to call script externally.  Let's have a look. <html> <head> </head> <body> click on the image </body> </html> Using the tag <script type="text/javascript" src="functions.js"> </script> we can call the script externally. Always write script in file with extension ".js". functions.js: function imageswitch(){ var image = document.getElementById('switchimage'); if(image.src.match("one")) { image.src = "flower_two.jpg"; } else { image.src = "flower_one.jpg"; } } Note: Make sure that the both html and js file locations are the same or else defime them specifically