How use getDrawable() while using ViewPager - android

I was trying to use Drawable Animation in one of my Viewpager. But when I try to use getDrawable() method, it gives me null pointer exception. My ViewPager has 4 page. I think this is because my XML files are made in Viewpager and I cannot access them with this method. I already set a source for an ImageView in my Viewpager but still it doesn't work. Please have a look at my codes and help me.
My Main Activity:
import android.graphics.drawable.AnimationDrawable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new CustomPagerAdapter(this));
ImageView myAnimation = (ImageView)findViewById(R.id.imageView2);
final AnimationDrawable myAnimationDrawable = (AnimationDrawable)myAnimation.getDrawable();
myAnimationDrawable.start();
}
}
My ViewPager Adapter:
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject modelObject = ModelObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
and my enum to add new Pages:
public enum ModelObject {
RED(R.string.wp1, R.layout.wp1),
BLUE(R.string.wp2, R.layout.wp2),
LOL(R.string.wp3, R.layout.wp3),
WP(R.string.wp5,R.layout.wp4),
GREEN(R.string.wp4, R.layout.wp4);
private int mTitleResId;
private int mLayoutResId;
ModelObject(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
Please help me if you can.
sorry for bad English.

#Override
public void onPageSelected(int pos) {
//find your layout in with the position & then implement
ImageView myAnimation = (ImageView)findViewById(R.id.imageView2); // this imageview for particular viewpager page
final AnimationDrawable myAnimationDrawable = (AnimationDrawable)myAnimation.getDrawable();
myAnimationDrawable.start();
}

Related

Android: Change text in a PagerAdapter

I have a MainActivity which calls a fragment (ReadStory).
ReadStory has a ViewPager which uses a PagerAdapter.
The page has an image and a TextView at the bottom. (This example only shows the TextView)
All of this works well.
There's a requirement that when the user touches/clicks the TextView various words are highlighted in red. This also works well.
The problem I have is that the text (with red highlights) is displayed on the next screen not the current visible screen.
I have set a onClickListener on the TextView which sets the relevant parts to red and then sets the text on the TextView.
The ViewPager loads the current screen plus the previous and next screens. The TextView is 'attached' to the "nextScreen".
How do I change the TextView on the current screen?
I've searched for the answer for several days but I can't seem to find an answer. Any help would be appreciated.
My code - MainActivity
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button myButton;
ReadStory RS;
// *********************************************************************************************
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.button);
myButton.setOnClickListener(textViewClickListener);
}
// *********************************************************************************************
private View.OnClickListener textViewClickListener = new View.OnClickListener() {
public void onClick(View v) {
int[] mStory_resources = {R.string.S1P0, R.string.S1P1, R.string.S1P2, R.string.S1P3, R.string.S1P4, R.string.S1P5, R.string.S1P6, R.string.S1P7,
R.string.S1P8, R.string.S1P9, R.string.S1P10, R.string.S1P11};
int mStoryWords = R.string.S1words;
RS = new ReadStory();
Bundle args = new Bundle();
args.putIntArray("Story", mStory_resources);
args.putInt("storyWords", mStoryWords);
RS.setArguments(args);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack("readStory");
ft.replace(R.id.activity_main, RS);
ft.commit();
}
};
// *********************************************************************************************
}
ReadStory
import android.os.Bundle;
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 android.widget.RelativeLayout;
public class ReadStory extends Fragment {
static String currentString = "";
static String newString = "";
private static final String story = "Story";
private static final String storyWords = "storyWords";
private int[] mStory_resources;
private int mStory_words;
ViewPager viewPager;
CustomSwipeAdapter adapter;
public ReadStory() {
// Required empty public constructor
}
// *********************************************************************************************
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mStory_resources = getArguments().getIntArray(story);
mStory_words = getArguments().getInt(storyWords);
}
}
// *********************************************************************************************
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final RelativeLayout parent = (RelativeLayout) inflater.inflate(R.layout.read_story, container, false);
viewPager = (ViewPager) parent.findViewById(R.id.view_pager);
adapter = new CustomSwipeAdapter(getActivity());
adapter.story_resources = mStory_resources;
adapter.story_words = mStory_words;
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
currentString = getString(mStory_resources[position]);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return parent;
}
// *********************************************************************************************
}
PagerAdapter
import android.content.Context;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class CustomSwipeAdapter extends PagerAdapter{
int[] story_resources;
int story_words;
private TextView textView;
private Context ctx;
CustomSwipeAdapter(Context ctx)
{
this.ctx = ctx;
}
// *********************************************************************************************
#Override
public int getCount() {
return story_resources.length;
}
// *********************************************************************************************
#Override
public boolean isViewFromObject(View view, Object object) {
return (view==object);
}
// *********************************************************************************************
#SuppressWarnings("deprecation") // Put here as setText is deprecated as of API 16 - Jelly_bean
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater layoutInflater;
layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
textView = (TextView) item_view.findViewById(R.id.image_count);
textView.setText(story_resources[position]);
textView.setOnClickListener(textViewClickListener);
container.addView(item_view);
return item_view;
}
// *********************************************************************************************
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((RelativeLayout)object);
}
// *********************************************************************************************
#SuppressWarnings("deprecation") // Put here as fromHtml is deprecated as of API 24 - N
private View.OnClickListener textViewClickListener = new View.OnClickListener() {
public void onClick(View v) {
String patternString = "\\b(" + ctx.getString(story_words) + ")\\b";
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(ReadStory.currentString);
StringBuffer bufStr = new StringBuffer();
while (matcher.find()) {
String rep = matcher.group();
matcher.appendReplacement(bufStr, "<font color='#EE0000'>" + rep + "</font>");
}
matcher.appendTail(bufStr);
ReadStory.newString = bufStr.toString();
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(ReadStory.newString));
} else {
textView.setText(Html.fromHtml(ReadStory.newString));
}
Toast.makeText(ctx, "Clicked", Toast.LENGTH_LONG).show();
}
};
// *********************************************************************************************
}
Using
((TextView)v).setText(Html.fromHtml(ReadStory.newString));
instead of
textView.setText(Html.fromHtml(ReadStory.newString));
There is reference problem with textView object it consists reference of next item.

Slide on gallery app

I'm currently working on a app that is a like a gallery app. The app need to load some images from the resources folder and when the user selects one, the app should load the selected image, and if the user slides the screen, the app should load the next image or the previous image.
The problem I have is that when I click the image the app always loads the first image. I try to use a intet with a int to solve it, but the program gives me an error.
I'm quite new in android programing, sorry if it is a simple question.
Here is the code of the app:
Main activity:
package com.example.erasor.pruebaslide;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Image1 (View view) {
Intent intent= new Intent(this, Slide.class);
startActivity(intent);
}
public void Image2 (View view) {
Intent intent = new Intent(this, Slide.class);
intent.putExtra("position", 2);
startActivity(intent);
}
}
Slide activity:
package com.example.erasor.pruebaslide;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class Slide extends AppCompatActivity {
private CustomPagerAdapter mCustomPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slide);
Intent intent = getIntent();
int position = intent.getIntExtra("position", 0);
mCustomPagerAdapter = new CustomPagerAdapter(this);
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mCustomPagerAdapter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
int[] mResources = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
};
class CustomPagerAdapter extends PagerAdapter {
Context mContext;
LayoutInflater mLayoutInflater;
public CustomPagerAdapter(Context context) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mResources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mLayoutInflater.inflate(R.layout.fragment_slide, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.image);
imageView.setImageResource(mResources[position]);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((RelativeLayout) object);
}
}
}
I think you are missing the part where you tell the mViewPager which position to display, try this:
mViewPager.setAdapter(mCustomPagerAdapter);
mViewPager.setCurrentItem(position);

How to make the Swipe view loop

I am trying to make an app were the images are shown in a list view .But I am not able to loop the View Pager.Show that after the last image first image comes . Here is my code.I tried the basic java method but It is not working
package com.union.pr26;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
public class MainActivity extends Activity {
ViewPager viewPager;
CustomeSwipeAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager=(ViewPager)findViewById(R.id.viewpager);
adapter=new CustomeSwipeAdapter(this);
viewPager.setAdapter(adapter);
}
}
ADAPTER
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class CustomeSwipeAdapter extends PagerAdapter {
private Context ctx;
final int position = 0;
private LayoutInflater layoutInflater;
private int []imgID ={R.drawable.img1,R.drawable.img2,R.drawable.img3};
public CustomeSwipeAdapter(Context ctx) {
this.ctx=ctx;
}
#Override
public int getCount() {
return imgID.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view==(LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater =(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view =layoutInflater.inflate(R.layout.extra,container,false);
ImageView imageView =(ImageView)item_view.findViewById(R.id.imageView);
if(position>=3){
position=-imgID.length;
position--;
}
imageView.setImageResource(imgID[position]);
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
In your mainActivity:
List<Integer> galImages = new ArrayList<>();
galImages.add(R.drawable.one);
galImages.add(galImages.get(0));
galImages.add(0,galImages.get(galImages.size()-2));
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this,galImages);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(1, false);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) { //this is triggered when the switch to a new page is complete
final int lastPosition = viewPager.getAdapter().getCount() - 1;
int currentPosition = viewPager.getCurrentItem();
if (currentPosition == lastPosition) {
viewPager.setCurrentItem(1, false); //false so we don't animate
} else if (currentPosition == 0) {
viewPager.setCurrentItem(lastPosition - 1, false);
}
}
}
});
In my example,i added one image in my list,then added it again.And then in onPageScrollStateChaged i loop it over and over again
You have to use an InfiniteViewPager. Here is the link for achieving the same.
GitHub Link

viewpager implemented in gridview position

I am working on an application that have to have a GridView in the main activity containing images.
When an image is clicked, it has to open in another Activity in a bigger size. In this Activity, a ViewPager has to be implemented so that I can swipe right and left to change between the images.
The problem is that when i click on an image, the first image of the images appear firstly (argentina flag) and then the viewpager works .. how can i make it start by the image that i clicked ?
This is my main activity code :
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.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
public class MainActivityPager extends ActionBarActivity
{
static int[] FLAG;
ViewPager viewPager;
PagerAdapter adapter;
GridView gridview;
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_pager);
FLAG = new int[] { R.drawable.flag_of_argentina, R.drawable.flag_of_brazil,
R.drawable.flag_of_england, R.drawable.flag_of_france,
R.drawable.flag_of_germany, R.drawable.flag_of_italy, R.drawable.flag_of_spain,
R.drawable.flag_of_uruguay };
AdapterGrid adapter = new AdapterGrid(MainActivityPager.this, FLAG);
gridview = (GridView) findViewById(R.id.gridView1);
gridview.setAdapter(adapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
Intent intent = new Intent(view.getContext(), ActivityImage.class);
intent.putExtra("position", position);
count = gridview.getCount();
intent.putExtra("count", count);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my AdapterGrid class code :
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class AdapterGrid extends BaseAdapter
{
private int[] mFlag;
private Context mContext;
public AdapterGrid(Context context, int[] flag) {
//super(context, flag);
mContext = context;
mFlag = flag;
}
#Override
public int getCount() {
return mFlag.length;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View grid;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
imageView.setImageResource(mFlag[position]);
} else {
grid = (View) convertView;
}
return grid;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
This is my ActivityImage code :
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class ActivityImage extends FragmentActivity
{
private static int COUNT;
MyAdapter mAdapter;
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
Intent intent = getIntent();
COUNT = intent.getExtras().getInt("count");
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return COUNT;
}
#Override
public Fragment getItem(int position) {
return FragmentImage.init(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_image, menu);
return true;
}
}
This is my FragmentImage class code :
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.ImageView;
public class FragmentImage extends Fragment {
int fragVal;
static FragmentImage init(int pos) {
FragmentImage frag = new FragmentImage();
Bundle args = new Bundle();
args.putInt("val", pos);
frag.setArguments(args);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragVal = getArguments() != null ? getArguments().getInt("val") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.fragment_image, container,
false);
ImageView imageView = (ImageView) layoutView.findViewById(R.id.imageView1);
imageView.setImageResource(MainActivityPager.FLAG[fragVal]);
return layoutView;
}
}
Thanks.
You set the position intent.putExtra("position", position); but never use it.
get it and
set after
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(CurrentPosition);

Android: tabs with swipe not showing listfragment

I'm dealing with this tutorial: http://www.lucazanini.eu/2012/android/tabs-and-swipe-views/?lang=en .
The problem is that if I set as layout of the tab a simple static layout, like this (as the tutorial does), everything works fine:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/body1" />
</LinearLayout>
But I need the tab to be a ListFragment, and the matter is that my ListFragment shows nothing at all.
Here is the code. Don't desperate: I put lots of code but I think you will probably just need to look at the classes SongsFragment and SongsListAdapter (well, I am not sure because I were it I would not write here, however I suppose it because with a static layout everything works fine!)
EDIT: I post just one listfragment in the exemple, however it seems that every listfragment has the same issue
EDIT: probably the problem is that I need to use a method to show the fragment when the tab is selected
THANKS A LOT
Activity:
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class PlayerActivity extends FragmentActivity implements
ActionBar.TabListener {
CollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mCollectionPagerAdapter = new CollectionPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select
// the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if
// we have a reference to the Tab.
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mCollectionPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mCollectionPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// TODO Auto-generated method stub
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
SongsFragment
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class SongsFragment extends ListFragment {
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class SongsFragment extends ListFragment {
List<String[]> songs;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
songs = SongsDataSource.getInstance().getAllSongs();
List<String[]> values = new ArrayList<String[]>();
if (songs.size() == 0) {
values.add(new String[] { "No files found", "Try to update your database", "" });
}
for (String[] song : songs) {
values.add(new String[] { song[1], song[2], song[0] });
}
SongsListAdapter adapter = new SongsListAdapter(getActivity().getApplicationContext(),
R.layout.songs, R.id.songsFragment_titleTextView,R.id.songsFragment_artistTextView, values);
setListAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.songs, container, false);
return view;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
}
}
SongsListAdapter
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SongsListAdapter extends ArrayAdapter<List<String[]>> {
private final Context context;
private final List<String[]> values;
private final Integer listViewId;
private final Integer titleTextViewId;
private final Integer artistTextViewId;
public SongsListAdapter(Context context, Integer listViewId, Integer titleTextViewId,
Integer artistTextViewId, List values) {
super(context, listViewId, values);
this.context = context;
this.listViewId = listViewId;
this.values = values;
this.titleTextViewId = titleTextViewId;
this.artistTextViewId = artistTextViewId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(listViewId, parent, false);
TextView titleView = (TextView) rowView.findViewById(titleTextViewId);
TextView artistView = (TextView) rowView.findViewById(artistTextViewId);
titleView.setText(values.get(position)[0]);
artistView.setText(values.get(position)[1]);
return rowView;
}
}
PagerAdapter
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class CollectionPagerAdapter extends FragmentPagerAdapter {
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return MyApplication.getInstance().infoFragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
String tabLabel = null;
if(0 <= position && position < MyApplication.getInstance().infoFragments.length) {
tabLabel = MyApplication.getInstance().infoFragments[position].getLabel();
}
return tabLabel;
}
}
TabFragment class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A fragment that launches other parts of the demo application.
*/
public class TabFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
if(0 <= position && position < MyApplication.getInstance().infoFragments.length) {
tabLayout = MyApplication.getInstance().infoFragments[position].getLayout();
}
View rootView = inflater.inflate(tabLayout, container, false);
return rootView;
}
}
MyApplication class
import android.app.Application;
public class MyApplication extends Application {
//SIGLETON DECLARATION
private static MyApplication mInstance = null;
public static MyApplication getInstance() {
if (mInstance == null) {
mInstance = new MyApplication();
}
return mInstance;
}
public static InfoFragment[] infoFragments = new InfoFragment[] {
new InfoFragment("Songs", R.layout.songs)
};
public static class InfoFragment {
private String label;
private int layout;
public InfoFragment(String label, int layout) {
this.label = label;
this.layout = layout;
}
public String getLabel() {
return label;
}
public int getLayout() {
return layout;
}
}
}
Oh, it seems like you never actually return your SongsFragment in your getItem() method. It actually seems like you never use it!
#Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}

Categories

Resources