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

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;

Passing Images between Activities in Android

in First Activity: Intent intent=new Intent(FirstClass.this, SecondClass.class); Bundle bundle=new Bundle(); bundle.putInt("image",R.drawable.ic_launcher); intent.putExtras(bundle); startActivity(intent); in Second Acticity: Bundle bundle=this.getIntent().getExtras(); int pic=bundle.getInt("image"); v.setImageResource(pic); another method: in First Activity: Drawable drawable=imgv.getDrawable(); Bitmap bitmap= ((BitmapDrawable)drawable).getBitmap(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] b = baos.toByteArray(); Intent intent=new Intent(Passimage.this,myclass.class); intent.putExtra("picture", b); startActivity(intent); in Second Acticity: Bundle extras = getIntent().getExtras(); byte[] b = extras.getByteArray("picture"); Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.lengt

Show and Resume Android Soft-Keyboard

Code to show keyboard: InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(yourEditText,InputMethodManager.SHOW_IMPLICIT); Code resume keyboard : InputMethodManager imm = (InputMethodManager)gettSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);