Android: ViewPager with ImageView - android

I´m new in working with ViewPager. So i took a tutorial and it all works now. After the tutorial, I have a ViewPager with a TextView on it.
Now, I want to add an ImageView to this TextView. Where do I have to start?
Here´s my code:
public static final MyFragment newInstance(String message){
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
View v = inflater.inflate(R.layout.activity_my_fragment, container, false);
TextView messageTextView = (TextView)v.findViewById(R.id.tvTest);
messageTextView.setText(message);
return v;
}
and
public class Bilderbuch extends FragmentActivity {
MyPageAdapter pageAdapter;
int id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bilderbuch);
id = getIntent().getIntExtra("kinderid", 0);
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
DBHelper dbh = new DBHelper(this);
Cursor c = dbh.selectEreignis(id);
int i = 0;
while(c.moveToNext())
{
fList.add(MyFragment.newInstance(c.getString(c.getColumnIndex("ereignisname"))));
i++;
}
fList.add(MyFragment.newInstance("Fragment 1"));
fList.add(MyFragment.newInstance("Fragment 2"));
fList.add(MyFragment.newInstance("Fragment 3"));
return fList;
}
private class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}

You have to write a new Fragment. In to the layout of the Fragment you must add an ImageView. Than you cant make something like below in your MyPagerAdapter:
private class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MyFragment();
case 1:
return new ImageFragment(R.drawable.my_image); // The second view will return your ImageFragment
default:
return null;
}
}
#Override
public int getCount() {
return this.fragments.size();
}
}

you have "activity_my_fragment.xml" inisde it put this code , with a image src .
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/your_image_name_inside_resDrawable_folder"
/>
Edited :
use this article : http://architects.dzone.com/articles/android-tutorial-using

Related

Catch the changing of slide in a ViewPager

I have implemented a ViewPager in order to swipe between two Fragments like such:
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.statistics_general_vp, container, false);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mStatisticsPagerAdapter = new StatisticsPagerAdapter(getActivity().getSupportFragmentManager());
mViewPager.setAdapter(mStatisticsPagerAdapter);
return view;
}
public class StatisticsPagerAdapter extends FragmentStatePagerAdapter {
public StatisticsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return new GeneralStatistics();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
But for now my two slides display the same Fragment.
How may I have slide 1 display Fragment 1 and slide 2 Fragment 2?
have u created fragment1 and fragment 2 seperately?? if yes then do this - in activity holding these two fragments.
private void createViewPager(ViewPager viewPager) {
Log.d("activity", "viewpager");
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Fragment1(), "");
adapter.addFrag(new Fragment2(), "");
viewPager.setAdapter(adapter);
}
create fragment like this -
public class Fragment1 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.transaction_layout, container, false);
return v;
}
}
create viewpager like this -
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
or if you want to make tab with icons use this method -
private void createTabIcons() {
Log.d("activity", "createtabicons");
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.tab_item2, null);
tabOne.setText("QR Scan");
tabOne.setTypeface(MRR);
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.image1, 0, 0);
tabOne.setCompoundDrawablePadding(5);
tabLayout.getTabAt(0).setCustomView(tabOne);
tabLayout.getTabAt(0).getCustomView().setSelected(true);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.tab_item2, null);
tabTwo.setText("Mobile No.");
tabTwo.setTypeface(MRR);
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.image3, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
tabTwo.setCompoundDrawablePadding(5);
}
Hello i show you what i doing, i got 2 fragments in mainActivity
private void addFragments() {
List<Fragment> fragments = new ArrayList<>();
chatFragment = new ChatFragment();
remoteFragment = new RemoteFragment();
fragments.add(remoteFragment);
fragments.add(chatFragment);
MyPageAdapter adapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(TAB_REMOTE_POSITION)
.setIcon(getDrawable(R.drawable.ic_settings_remote_white_24dp));
tabLayout.getTabAt(TAB_SOCIAL_POSITION)
.setIcon(getDrawable(R.drawable.ic_group_white_24dp));
}
Here is my adapter:
class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
and on OnCreate u should
addFragments();
also i bind the views with ButterKnife
#Bind(R.id.view_pager)
ViewPager viewPager;
#Bind(R.id.tab_layout)
TabLayout tabLayout;
but u can static implement this with android
And remember that u have listeners:
private void pageChangeListener() {
viewPager.addOnPageChangeListener(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) {
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService
(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
});
}

TabLayout and ViewPager not showing correctly with two fragments

I have two fragments (Same class- PlayerFragment) and I set the ViewPager with this method:
private void setupViewPager(ViewPager viewPager) {
FragmentManager fManager = getSupportFragmentManager();
ViewPagerAdapter adapter = new ViewPagerAdapter(fManager);
Bundle args1 = new Bundle();
args1.putInt("Id",1);
PlayerFragment pf1 = new PlayerFragment();
pf1.setArguments(args1);
adapter.addFrag(pf1, "Players 1");
Bundle args2 = new Bundle();
args2.putInt("Id",2);
PlayerFragment pf2 = new PlayerFragment();
pf2.setArguments(args2);
adapter.addFrag(pf2, "Players 2");
viewPager.setAdapter(adapter);
}
I have two tabs but only the first tab shows me content, the other tab is empty.
And the first tabs shows me the contentent of the second one.
static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
In the activity where I use the fragments I have this code:
final ViewPager viewPager = (ViewPager) findViewById(R.id.vpTeam);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabsTeam);
tabLayout.setupWithViewPager(viewPager);
Thanks!
Edit: This is the PlayerFragment
public class PlayerFragment extends Fragment {
private ProgressDialog progressDialog;
private List<Player> myPlayers = new ArrayList<>();
private int myTeamId = 14;
public PlayerFragment(){
}
public static PlayerFragment newInstance(int someInt) {
PlayerFragment myFragment = new PlayerFragment();
Bundle args = new Bundle();
args.putInt("TeamId", someInt);
myFragment.setArguments(args);
return myFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
Bundle args = getArguments();
if(args!=null) {
myTeamId = args.getInt("TeamId");
}
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_player, container, false);
new BackgroundAsyncTask().execute();
return view;
}
}
Can you post the code of PlayerFragment? I'm pretty sure that the error is that you have the variables in that class as static. Also try to use the "new instance()" way for creating fragments --> Best practice for instantiating a new Android Fragment

How to update only current fragment's view in viewpager?

I used a ViewPager with FragmentPagerAdapter in my app. I created 4 fragments. Also I used EventBus library to refresh current fragment's background color. When I changed the page, onEvent method was triggered, then all 4 fragments' background color was changed. But I want to change only current fragment's background color. How can I fix this bug? Sorry for my bad English.
ViewPager as below :
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
MyPageViewActivity as below :
public class PageViewActivity extends FragmentActivity {
MyPagerAdapter pageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
List<Fragment> fragments = getFragments();
pageAdapter = new MyPagerAdapter(getSupportFragmentManager(), fragments);
pager.setAdapter(pageAdapter);
pager.setOffscreenPageLimit(4);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
EventBus.getDefault.post(new TriggerEvent(position));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(MyFragment.newInstance("1"));
fList.add(MyFragment.newInstance("2"));
fList.add(MyFragment.newInstance("3"));
fList.add(MyFragment.newInstance("4"));
return fList;
}
}
finally MyFragment.class
public class MyFragment extends Fragment {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
RelativeLayout relativeLayout;
String msg;
public static final MyFragment newInstance(String message) {
MyFragment f = new MyFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
msg = getArguments().getString(EXTRA_MESSAGE);
relativeLayout = (RelativeLayout) v.findViewById(R.id.relativelayout);
return v;
}
public void onEvent(TriggerEvent trigger) {
relativeLayout.setBackgroundColor(randomColor());
}
}
try this,
public void onEvent(TriggerEvent trigger) {
if(isCurrentFragment){
relativeLayout.setBackgroundColor(randomColor());
}
}

Android ViewPager in ViewPager only one child has data

I know there is a lot of different issues about PageViewers but I can't find solution to my problem.
The problem is that in my app i have one PageViewin another lets say that in PageViewA i have PageView B. In A i keep some informations in TextViews and B. B keeps ImageView and should display images for my fragments. A has few pages and on every page I have right data on TextViews but only one(the first visible one) contains images. When i switch pages none of B ViewPager have images but have right TextViews.
Adapter for A and getFragments() method:
class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> pages;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.pages = fragments;
}
#Override
public Fragment getItem(int position) {
return this.pages.get(position);
}
#Override
public int getCount() {
return this.pages.size();
}
}
private ArrayList<Fragment> getFragments(){
ArrayList<Fragment> fList = new ArrayList<Fragment>();
for(int i=0;i<diary.getList().get(index).events.size();i++){
fList.add(EventPageFragment.newInstance("",index,i));
}
return fList;
}
CreateView and adapter in EventPageFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
int index = getArguments().getInt(INDEX);
int eventIndex = getArguments().getInt(EVENT);
View v = inflater.inflate(R.layout.page_eventview, container, false);
TextView title = (TextView)v.findViewById(R.id.event_past_title);
TextView date = (TextView)v.findViewById(R.id.event_past_date);
TextView description = (TextView)v.findViewById(R.id.event_past_desc);
title.bringToFront();
images = getFragments(index,eventIndex);
pager = (ViewPager)v.findViewById(R.id.event_pager);
pageAdapter = new MyPageAdapter(getFragmentManager(),images);
pager.setAdapter(pageAdapter);
pageAdapter.notifyDataSetChanged();
pager.invalidate();
title.setText(diary.getList().get(index).events.get(eventIndex).getTitle());
date.setText(getResources().getString(R.string.date)+": "+diary.getList().get(index).events.get(eventIndex).getDate()[0]+"/"+
diary.getList().get(index).events.get(eventIndex).getDate()[1]+"/"+
diary.getList().get(index).events.get(eventIndex).getDate()[2]);
description.setText(getResources().getString(R.string.description)+": "+diary.getList().get(index).events.get(eventIndex).getDescription());
return v;
}
class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> images;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.images = fragments;
}
#Override
public Fragment getItem(int position) {
return this.images.get(position);
}
#Override
public int getCount() {
return this.images.size();
}
}
private ArrayList<Fragment> getFragments(int index, int event){
ArrayList<Fragment> fList = new ArrayList<Fragment>();
for(int i=0;i<diary.getList().get(index).events.get(event).photoReference.size();i++){
fList.add(PhotoFragment.newInstance("",index,event,i));
}
return fList;
}
And finally PhotoFragment that represents images in B:
public static final PhotoFragment newInstance(String message, int personIndex, int eventIndex, int photoIndex)
{
PhotoFragment f = new PhotoFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
bdl.putInt(INDEX, personIndex);
bdl.putInt(EVENT, eventIndex);
bdl.putInt(PHOTO, photoIndex);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
int index = getArguments().getInt(INDEX);
int eventIndex = getArguments().getInt(EVENT);
int photoIndex = getArguments().getInt(PHOTO);
View v = inflater.inflate(R.layout.page_photo_fragment, container, false);
ImageView image = (ImageView)v.findViewById(R.id.event_photo_image);
image.setImageBitmap(PhotoManager.decodeFile(diary.getList().get(index).events.get(eventIndex).photoReference.get(photoIndex),300));
return v;
}
}
I have no idea why only one EventPage loads images from PhotoFragment

NullPointerException a call tag fragment ViewPager

Need help, trying to invoke a method fragment of Activity, I think that is not correct ask tags for fragments.
so ask tags:
public class TitleAdapter extends FragmentPagerAdapter {
public final String titles[] = new String[] { "A", "B", "C" };
public final Fragment frags[] = new Fragment[titles.length];
public TitleAdapter(FragmentManager fm) {
super(fm);
frags[0] = new FragmentA();
fm.beginTransaction().add(frags[0], "fragA").commit();
frags[1] = new FragmentB();
fm.beginTransaction().add(frags[1], "fragB").commit();
frags[2] = new FragmentC();
fm.beginTransaction().add(frags[2], "fragC").commit();
}
#Override
public CharSequence getPageTitle(int position) {
Log.v("TitleAdapter - getPageTitle=", titles[position]);
return titles[position];
}
#Override
public Fragment getItem(int position) {
Log.v("TitleAdapter - getItem=", String.valueOf(position));
return frags[position];
}
#Override
public int getCount() {
return frags.length;
}
}
Feel right from causing onCreate(Bundle savedInstanceState)
public class MainActivity extends FragmentActivity {
TitleAdapter titleAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(2);
FragmentManager fm = getSupportFragmentManager();
FragmentA fragment = (FragmentA)fm.findFragmentByTag("fragA");
fragment.bgStop();
Here the method itself
public class FragmentA extends Fragment {
final static String LOG_TAG = "myLogs";
static Button btnPlay;
public FragmentA() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
btnPlay = (Button) rootView.findViewById(R.id.btnStart);
return rootView;
}
public void bgPlay(){
btnPlay.setText("Play");
btnPlay.setBackgroundResource(R.drawable.play_button);
}
public void bgStop(){
btnPlay.setText("Stop");
btnPlay.setBackgroundResource(R.drawable.stop_button);
}
}
There are so many problems with that code. Here, let me fix that for you.
The following is untested, just edited in my favourite text editor.
public class TitleAdapter extends FragmentPagerAdapter {
public final String titles[] = new String[] { "A", "B", "C" };
public final Fragment frags[] = new Fragment[titles.length];
public TitleAdapter(FragmentManager fm) {
super(fm);
// do not commit any fragments here, the adapter handles that.
frags[0] = new FragmentA();
frags[1] = new FragmentB();
frags[2] = new FragmentC();
}
#Override
public CharSequence getPageTitle(int position) {
Log.v("TitleAdapter - getPageTitle=", titles[position]);
return titles[position];
}
#Override
public Fragment getItem(int position) {
Log.v("TitleAdapter - getItem=", String.valueOf(position));
return frags[position];
}
#Override
public int getCount() {
return frags.length;
}
}
Then in the activity:
public class MainActivity extends FragmentActivity {
TitleAdapter titleAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
final TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(2);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
Fragment fragment = titleAdapter.getItem(position);
// Ideally use some sort of interface here.
if (fragment instanceof FragmentA) {
((FragmentA) fragment).bgStop();
}
}
});
}
}

Categories

Resources