I am using view-pager with fragment and pass hash-map through bundle instance to fragment. But it does not show all images in view-pager , only 3rd image show by default.
I am stuck on this... Any help will be appreciable.
Below is my java code
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
List<Fragment> fragments1;
public MyPagerAdapter adapter1;
static final ArrayList<HashMap<String, Integer>> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.pager1);
fragments1 = getFragments1();
adapter1 = new MyPagerAdapter(getSupportFragmentManager(), fragments1);
viewPager.setAdapter(adapter1);
}
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();
}
#Override
public int getItemPosition (Object object)
{
if (object instanceof MyImageSlider ) {
return POSITION_NONE;
}
return POSITION_UNCHANGED;
}
}
private List<Fragment> getFragments1() {
List<Fragment> fList = new ArrayList<>();
for(int i = 0; i < 5; i++){
HashMap<String, Integer> map = new HashMap<>();
map.put("0",R.drawable.first);
map.put("1",R.drawable.second);
map.put("2",R.drawable.three);
map.put("3",R.drawable.four);
map.put("4",R.drawable.xiaomi);
list.add(map);
fList.add(MyImageSlider.newInstance(list.get(i)));
}
return fList;
}
public static class MyImageSlider extends Fragment {
HashMap<String, Integer> imageid;
ArrayList<HashMap<String, Integer>> listArray = new ArrayList<>();
public static MyImageSlider newInstance(HashMap<String, Integer> id)
{
MyImageSlider slider=new MyImageSlider();
Bundle b=new Bundle();
b.putSerializable("imageid", id);
slider.setArguments(b);
return slider;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageid=(HashMap<String, Integer>) getArguments().getSerializable("imageid");
listArray.add(imageid);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_main, container, false);
ImageView iv=(ImageView)view.findViewById(R.id.img);
for (String key : imageid.keySet()) {
iv.setImageResource(imageid.get(key);
}
return view;
}
}
}
why are you creating List of Fragment, you can create a single Fragment which is holding imageView and pass List of images through adapter and show image on that Fragment.
Please check below code -
and let me know if you have any concern.
// This is your MainActivity.java
package com.sample.stack;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager1);
HashMap<String,Integer> sliderDataList = new HashMap<String,Integer>();
sliderDataList.put("0",R.drawable.tc);
sliderDataList.put("1",R.drawable.tc);
sliderDataList.put("2",R.drawable.tc);
sliderDataList.put("3",R.drawable.tc);
sliderDataList.put("4",R.drawable.tc);
PagerAdapter adapter1 = new PagerAdapter(getSupportFragmentManager(), sliderDataList, MainActivity.this);
viewPager.setAdapter(adapter1);
}
}
// This is your FragmentPagerAdapter
package com.sample.stack;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.HashMap;
/**
* Created by on 06-12-2016.
*/
public class PagerAdapter extends FragmentPagerAdapter {
private final HashMap<String, Integer> hMap;
private final Context context;
public PagerAdapter(FragmentManager fm, HashMap<String,Integer> hMap, Context context) {
super(fm);
this.hMap=hMap;
this.context=context;
}
#Override
public Fragment getItem(int position) {
return new SliderFragment(hMap,context,position);
}
#Override
public int getCount() {
return hMap.size();
}
}
// This is your Fragent containg ImageView
package com.sample.stack;
import android.annotation.SuppressLint;
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.ImageView;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by Syscraft on 06-12-2016.
*/
#SuppressLint("ValidFragment")
public class SliderFragment extends Fragment {
private final HashMap<String, Integer> urls;
private int imageResourceId;
private Context ctx;
public SliderFragment(HashMap<String,Integer> urls, Context c,
int pos) {
this.urls = urls;
this.imageResourceId = pos;
this.ctx = c;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.slider_adapter, container, false);
final ImageView imageView = (ImageView) view
.findViewById(R.id.sliderImages);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(urls.get(imageResourceId+""));
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return view;
}
}
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
public PagerAdapter adapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager1);
final HashMap<String,Integer> sliderDataList = new HashMap<String,Integer>();
sliderDataList.put("0",R.drawable.first);
sliderDataList.put("1",R.drawable.second);
sliderDataList.put("2",R.drawable.three);
sliderDataList.put("3",R.drawable.four);
sliderDataList.put("4",R.drawable.xiaomi);
adapter1 = new PagerAdapter(getSupportFragmentManager(), sliderDataList, MainActivity.this);
viewPager.setAdapter(adapter1);
// sliderDataList.remove("3");
adapter1.notifyDataSetChanged();
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
remove("3");
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void remove(String s){
adapter1.remove(s);
}
public class PagerAdapter extends FragmentPagerAdapter {
private final HashMap<String, Integer> hMap;
private final Context context;
public PagerAdapter(FragmentManager fm, HashMap<String,Integer> hMap, Context context) {
super(fm);
this.hMap=hMap;
this.context=context;
}
#Override
public Fragment getItem(int position) {
return new SliderFragment(hMap,context,position);
}
#Override
public int getCount() {
return hMap.size();
}
public void remove(String s){
Iterator<Map.Entry<String,Integer>> iter = hMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String,Integer> entry = iter.next();
if(s.equalsIgnoreCase(entry.getKey())){
iter.remove();
}
}
hMap.remove(s);
adapter1.notifyDataSetChanged();
}
}
#SuppressLint("ValidFragment")
public static class SliderFragment extends Fragment {
private final HashMap<String, Integer> urls;
private int imageResourceId;
private Context ctx;
public SliderFragment(HashMap<String,Integer> urls, Context c, int pos) {
this.urls = urls;
this.imageResourceId = pos;
this.ctx = c;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_main, container, false);
final ImageView imageView = (ImageView) view
.findViewById(R.id.img);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(urls.get(imageResourceId +""));
return view;
}
}
}
Related
I'm new in Android Development, I'm currently learning in TabLayout with Viewpager2.
I have hardcoded the Fragments in my adapter. Btw I need to add all of my Fragment with list. So how can I add Fragment in list, or Arraylist. Please Help me.
Here is the adapter code:
public class ScreenSliderAdapter extends FragmentStateAdapter{
public ScreenSliderAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
if (position==0) {
return new BangladeshFragment();
} else if (position==1) {
return new BrazilFragment();
} else if (position==2) {
return new MaltaFragment();
}
return new BangladeshFragment();
}
#Override
public int getItemCount() {
return 3;
}
}
Here is Main Activity Code:
public class MainActivity extends AppCompatActivity {
FragmentManager fm;
ScreenSliderAdapter sa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fm = getSupportFragmentManager();
sa = new ScreenSliderAdapter(fm,getLifecycle());
ViewPager2 pager = findViewById(R.id.pager);
TabLayout tabLayout = findViewById(R.id.tabLayoutID);
tabLayout.addTab(tabLayout.newTab().setText("Bangladesh"));
tabLayout.addTab(tabLayout.newTab().setText("Brazil"));
tabLayout.addTab(tabLayout.newTab().setText("Malta"));
pager.setAdapter(sa);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
pager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
tabLayout.selectTab(tabLayout.getTabAt(position));
}
});
}
}
Activity
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import java.util.ArrayList;
public class MyActivity extends AppCompatActivity {
ViewPager2 myViewPager2;
MyAdapter MyAdapter;
private ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
myViewPager2 = findViewById(R.id.view_pager);
arrayList.add("Item 1");
arrayList.add("Item 2");
arrayList.add("Item 3");
arrayList.add("Item 4");
arrayList.add("Item 5");
MyAdapter = new MyAdapter(this, arrayList);
myViewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
myViewPager2.setAdapter(MyAdapter);
}
}
New Features
myViewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
Log.e("Selected_Page", String.valueOf(position));
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
MyAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private ArrayList<String> arrayList = new ArrayList<>();
public MyAdapter(Context context, ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.tvName.setText(arrayList.get(position));
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvName;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tvName);
}
}
}
I am using view-pager with fragment in my application. i want to add and remove any key/value from hash-map but it gives me null pointer exception. there are 5 elements in hash-map if i remove last key from map then it works fine. How to solve it.
Below is my problem code :
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
public PagerAdapter adapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager1);
final HashMap<String,Integer> sliderDataList = new HashMap<String,Integer>();
sliderDataList.put("0",R.drawable.first);
sliderDataList.put("1",R.drawable.second);
sliderDataList.put("2",R.drawable.three);
sliderDataList.put("3",R.drawable.four);
sliderDataList.put("4",R.drawable.xiaomi);
adapter1 = new PagerAdapter(getSupportFragmentManager(), sliderDataList, MainActivity.this);
viewPager.setAdapter(adapter1);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
remove("3");
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void remove(String s){
adapter1.remove(s);
}
public class PagerAdapter extends FragmentStatePagerAdapter {
private HashMap<String, Integer> hMap;
private final Context context;
public PagerAdapter(FragmentManager fm, HashMap<String,Integer> hMap, Context context) {
super(fm);
this.hMap=hMap;
this.context=context;
}
#Override
public int getItemPosition (Object object)
{
return POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
return new SliderFragment(hMap,context,position);
}
#Override
public int getCount() {
return hMap.size();
}
public void remove(String s){
hMap.remove(s);
adapter1.notifyDataSetChanged();
}
}
#SuppressLint("ValidFragment")
public static class SliderFragment extends Fragment {
private HashMap<String, Integer> urls;
private int imageResourceId;
ImageView imageView;
private Context ctx;
public SliderFragment(HashMap<String,Integer> urls, Context c, int pos) {
this.urls = urls;
this.imageResourceId = pos;
this.ctx = c;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_main, container, false);
imageView = (ImageView) view.findViewById(R.id.img);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(urls.get(imageResourceId +""));
return view;
}
}
}
public void remove(String s){
if(sliderDataList.containskey("3"))
{
containskey.remove("3");
adapter1.notifydataSetChanged();
}
}
Try this:
Iterator<Map.Entry<String,String>> iter = TestMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String,String> entry = iter.next();
if("Sample".equalsIgnoreCase(entry.getValue())){
iter.remove();
}
}
if you just want to remove the null pointer exception, then add this:
if (urls.get(imageResourceId + "") != null)
imageView.setImageResource(urls.get(imageResourceId + ""));
I have a MainActivity and Three Fragments with recyclerViews inside the three fragments, the recyclerview contain two textviews, i want the user to click on the recyclerview and the text in should be passed on to the new activity, i am a little bit new so i would appreciate it if you can give me detailed code and some explanation.
I want to click on an item in the recyclerview and that should open a new activity, data(text) should be passed from the recyclerview to the new activity.
Here is my code for the HymnModel.java
public class HymnModel {
String title;
String song;
HymnModel(String title, String song){
this.title=title;
this.song=song;
}
public String getTitle() {return title;
}
public String getSong() {
return song;
}
}
Here is the code for ItemVeiwHolder.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.tutorialsbuzz.recyclerview.R;
public class ItemViewHolder extends RecyclerView.ViewHolder {
public TextView title_textview;
public TextView song_textview;
public ItemViewHolder(View itemView) {
super(itemView);
itemView.setClickable(true);
title_textview = (TextView) itemView.findViewById(R.id.song_title);
song_textview = (TextView) itemView.findViewById(R.id.song);
}
public void bind(HymnModel hymnModel) {
title_textview.setText(hymnModel.getTitle());
song_textview.setText(hymnModel.getSong());
}
}
Here is my Adapter class
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.tutorialsbuzz.recyclerview.R;
import java.util.ArrayList;
import java.util.List;
public class RVAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private List<HymnModel> mCountryModel;
private List<HymnModel> mOriginalCountryModel;
public RVAdapter(List<HymnModel> mCountryModel) {
this.mCountryModel = mCountryModel;
this.mOriginalCountryModel = mCountryModel;
}
#Override
public void onBindViewHolder(ItemViewHolder itemViewHolder, int i) {
final HymnModel model = mCountryModel.get(i);
itemViewHolder.bind(model);
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false);
return new ItemViewHolder(view);
}
#Override
public int getItemCount() {
return mCountryModel.size();
}
public void setFilter(List<HymnModel> countryModels){
mCountryModel = new ArrayList<>();
mCountryModel.addAll(countryModels);
notifyDataSetChanged();
}
}
Here is the code for one my fragments
public class TabOneFragment extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView recyclerview;
private List<HymnModel> mHymnModel;
private RVAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_one_fragment, container, false);
recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerview.setLayoutManager(layoutManager);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
int numOfSongs = 32;
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
String [] titles = {HymnTitles.hymnTitle1, HymnTitles.hymnTitle2, HymnTitles.hymnTitle3, HymnTitles.hymnTitle4, HymnTitles.hymnTitle5,
HymnTitles.hymnTitle6, HymnTitles.hymnTitle7, HymnTitles.hymnTitle8, HymnTitles.hymnTitle9, HymnTitles.hymnTitle10, HymnTitles.hymnTitle11,
HymnTitles.hymnTitle12};
String [] songs = {Hymns.hymn1.substring(width/5), Hymns.hymn2, Hymns.hymn3, Hymns.hymn4, Hymns.hymn5, Hymns.hymn6, Hymns.hymn7, Hymns.hymn8, Hymns.hymn9, Hymns.hymn10, Hymns.hymn11, Hymns.hymn12};
mHymnModel = new ArrayList<>();
for (int i = 0; i < titles.length; i++) {
mHymnModel.add(new HymnModel(i + "." + " " + titles[i], " " + songs[i]));
}
adapter = new RVAdapter(mHymnModel);
recyclerview.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
MenuItemCompat.setOnActionExpandListener(item,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
adapter.setFilter(mHymnModel);
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
}
#Override
public boolean onQueryTextChange(String newText) {
final List<HymnModel> filteredModelList = filter(mHymnModel, newText);
adapter.setFilter(filteredModelList);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private List<HymnModel> filter(List<HymnModel> models, String query) {
query = query.toLowerCase();
final List<HymnModel> filteredModelList = new ArrayList<>();
for (HymnModel model : models) {
final String text = model.getSong().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
My MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_action_person,
R.drawable.ic_action_group,
R.drawable.ic_action_call
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TabOneFragment(), "Tab 1");
adapter.addFragment(new TabTwoFragment(), "Tab 2");
adapter.addFragment(new TabThreeFragment(), "Tab 3");
viewPager.setAdapter(adapter);
}
}
And lastly my ViewPageAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
Thank You.
Create an interface
public interface OnHymnClickListener {
void onHymnClick(HymnModel hymnModel);
}
Pass the listener to the adapter
public class RVAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private OnHymnClickListener listener;
public void setListener(OnHymnClickListener listener) {
this.listener = listener;
}
#Override
public void onBindViewHolder(ItemViewHolder itemViewHolder, int i) {
final HymnModel model = mCountryModel.get(i);
itemViewHolder.bind(model);
itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener != null) {
listener.onHymnClick(model);
}
}
});
}
}
Let your fragment implement it
public class TabOneFragment extends Fragment implements SearchView.OnQueryTextListener, OnHymnClickListener {
#Override
public void onHymnClick(HymnModel hymnModel) {
//put data to bundle and startActivity
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
adapter = new RVAdapter(mHymnModel);
adapter.setListener(this);
recyclerview.setAdapter(adapter);
}
}
Hello first of all you always want to start your activity from activity or fragment.
Never start it from adapter.
So in your adapter constructor add this
public AdapterName(......,Context context){
...your code.
this.mContext=context;
}
pass context there.
and than inside this method
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mContext instanceof YourActivityName){
((YourActivityName)mContext).yourDesiredMethod();
}
}
});
MainActivity.java
public class MainActivity extends ActionBarActivity {
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
private ArrayList<String> mLanguagesArray = null;
int Numboftabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
mLanguagesArray = new ArrayList<String>();
mLanguagesArray.addAll(extras.getStringArrayList("languages"));
Numboftabs = mLanguagesArray.size();
}
}
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
adapter = new ViewPagerAdapter(getSupportFragmentManager(),
mLanguagesArray, Numboftabs, MainActivity.this);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setViewPager(pager);
tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int arg0) {
refreshListInFragment(arg0);
}
});
}
protected void refreshListInFragment(int position) {
String currentLanguage = mLanguagesArray.get(position);
FragmentManager fm = getSupportFragmentManager();
ListviewFragment fragment = (ListviewFragment) fm
.findFragmentById(R.id.pager);
fragment.loadListview(currentLanguage);
}
}
ViewPagerAdapter.java
import java.util.ArrayList;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<String> Titles;
int NumbOfTabs;
Context mContext;
public ViewPagerAdapter(FragmentManager fm,
ArrayList<String> mLanguagesArray, int mNumbOfTabsumb,
Context context) {
super(fm);
Titles = new ArrayList<String>();
this.Titles = mLanguagesArray;
this.NumbOfTabs = mNumbOfTabsumb;
this.mContext = context;
}
#Override
public Fragment getItem(int position) {
ListviewFragment listfragment = new ListviewFragment(mContext);
return listfragment;
}
#Override
public CharSequence getPageTitle(int position) {
return Titles.get(position);
}
#Override
public int getCount() {
return NumbOfTabs;
}
}
ListviewFragment.java
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.ListView;
import android.widget.ProgressBar;
public class ListviewFragment extends Fragment {
ProgressBar progressbar;
ListView list;
ArrayList<RStore> mRstoreList = null;
RadioListAdapter adapter;
Context mContext;
Button tryagain;
String mCurrentLanguage = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.listviewfragment, container, false);
progressbar = (ProgressBar) v.findViewById(R.id.progressbar);
list = (ListView) v.findViewById(R.id.listview);
if (ListviewFragment.this.isMenuVisible()) {
if (mRstoreList == null) {
loadListview("English");
}
}
return v;
}
public void loadListview(final String currentlanguage) {
this.mCurrentLanguage = currentlanguage;
mRstoreList = new ArrayList<RStore>();
new AsyncTask<Void, Void, String>() {
private String jsonStr;
#Override
protected void onPreExecute() {
list.setVisibility(View.GONE);
progressbar.setVisibility(View.VISIBLE);
tryagain.setVisibility(View.GONE);
super.onPreExecute();
}
#Override
protected String doInBackground(Void... arg0) {
try {
String URL = ServiceUrls.MUSIC_PHP;
CustomHttpClient sh = new CustomHttpClient();
JSONObject jsonobjpost = new JSONObject();
jsonobjpost.put("languages", currentlanguage);
jsonStr = sh.makeServiceCall(URL, CustomHttpClient.POST,
jsonobjpost.toString());
System.out.println("MUSIC_PHP_Response " + jsonStr);
} catch (Exception e) {
e.printStackTrace();
}
return jsonStr;
}
#Override
protected void onPostExecute(String result) {
if (result == null || result.trim().equalsIgnoreCase("null")
|| result.trim().equalsIgnoreCase("")) {
progressbar.setVisibility(View.GONE);
super.onPostExecute(result);
return;
}
try {
String DUMMYJASON = result.toString();
JSONObject jsonObject = new JSONObject(DUMMYJASON);
JSONArray jsonArray = jsonObject.getJSONArray("Language");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String id = obj.getString("id");
String language = obj.getString("language");
String tittle = obj.getString("Tittle");
String link = obj.getString("link");
RStore storecon = new RStore();
storecon.setId(id);
storecon.setLanguage(language);
storecon.setTitle(tittle);
storecon.setLink(link);
mRstoreList.add(storecon);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new RadioListAdapter(mContext, mRstoreList);
list.setAdapter(adapter);
list.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
super.onPostExecute(result);
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public ListviewFragment(Context context) {
this.mContext = context;
}
}
I'm creating number of fragments dynamically using one fragment class called ListviewFragment and setting it as view page adapter. ListviewFragment contains listview which is populated dynamically from service. With my code everything is working fine the only problem is, sometimes the datas inside the fragments are not refreshing or updating with new values. In my case the listview is showing the previously loaded data but in background the service is called and the listview Adapter is updated but the updated listview is not showing in the fragment. Please see my code, and correct me if i made any mistake..Thanks in advance
Instead of calling a method with (currentLanguage) as a parameter in fragment from activity using findFragmentById, I've just passed (currentLanguage) as bundle in ViewPagerAdapter getItem() method and in ListviewFragment class onCreateView i got (currentlanguage) value using getArguments and passed it to (loadListview) method. Now everything works fine and clean.
ViewPagerAdapter.java
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putString("language", Titles.get(position));
ListviewFragment f = new ListviewFragment(mContext);
f.setArguments(args);
return f;
}
ListviewFragment.java
private void getarugs() {
Bundle args = getArguments();
mCurrentLanguage = args.getString("language");
loadListview(mCurrentLanguage);
}
In my app I want to use swipe views of four tabs inside a fragment. The four tabs are contains different fragments each and all the four fragments are sliding by swipe from right to left or vice versa. The fragments are working fine but the tabs are not visible within the fragment. Anyone have any solution for this. Thanks in advance :)
this is the main fragment which contains the tabs:-
public class DashboardTabFragment extends Fragment implements ActionBar.TabListener {
private static final String ARG_SECTION_NUMBER = "arg_section_number";
private String[] tabTitle = {"Cleanness", "Product Display", "Hygiene", "Asm Visits"};
public static DashboardTabFragment newInstance(int position) {
DashboardTabFragment fragment = new DashboardTabFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
return fragment;
}
private ViewPager viewPager;
public DashboardTabFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dashboard_tab, container, false);
setHasOptionsMenu(true);
ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();
assert actionBar != null;
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
TabPageAdapter tabPageAdapter = new TabPageAdapter(getActivity().getSupportFragmentManager(), getActivity());
viewPager.setAdapter(tabPageAdapter);
for (String aTabTitle : tabTitle)
actionBar.addTab(actionBar.newTab().setText(aTabTitle).setTabListener(this));
return rootView;
}
This is the adapter for fragments:-
public class TabPageAdapter extends FragmentPagerAdapter {
Context context;
public TabPageAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CleannessChartFragment(context);
case 1:
return new ProductDisplayChartFragment(context);
case 2:
return new HygieneChartFragment(context);
case 3:
return new AsmVisitsChartFragment(context);
}
return null;
}
#Override
public int getCount() {
return 4;
}
I found the solution. I used TabHost for tabs with viewpager.
This is my fragment :-
package com.itpp.trt;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TabHost;
public class DashboardTabFragment extends Fragment implements ViewPager.OnPageChangeListener {
private static final String ARG_SECTION_NUMBER = "arg_section_number";
private ViewPager mViewPager;
private TabHost tabHost;
private String[] tabSpec = {"Tab_1", "Tab_2", "Tab_3", "Tab_4"};
private String[] tabTitle = {"Cleanness", "Product Display", "Hygiene", "Asm Visits"};
private TabHost.TabContentFactory mFactory = new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
View v = new View(getActivity());
v.setMinimumHeight(0);
return v;
}
};
public static DashboardTabFragment newInstance(int position) {
DashboardTabFragment fragment = new DashboardTabFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
return fragment;
}
public DashboardTabFragment() {
tabHost = null;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dashboard_tab, container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.pager);
mViewPager.setAdapter(new TabPageAdapter(getChildFragmentManager(), getActivity()));
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
tabHost.setup();
mViewPager.setOnPageChangeListener(this);
for (int i = 0; i < tabSpec.length; i++) {
tabHost.addTab(tabHost.newTabSpec(tabSpec[i]).setIndicator(tabTitle[i]).setContent(mFactory));
}
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
if (tabId.equals("Tab_1")) {
mViewPager.setCurrentItem(0);
} else if (tabId.equals("Tab_2")) {
mViewPager.setCurrentItem(1);
} else if (tabId.equals("Tab_3")) {
mViewPager.setCurrentItem(2);
} else if (tabId.equals("Tab_4")) {
mViewPager.setCurrentItem(3);
}
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MyActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onDetach() {
super.onDetach();
}
}
This is my tabpager adapter :-
package com.itpp.trt;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by biswajit on 28-11-14.
*/
public class TabPageAdapter extends FragmentStatePagerAdapter{
Context context;
public TabPageAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CleannessChartFragment(context);
case 1:
return new ProductDisplayChartFragment(context);
case 2:
return new HygieneChartFragment(context);
case 3:
return new AsmVisitsChartFragment(context);
}
return null;
}
#Override
public int getCount() {
return 4;
}
}
Hope this helps other. Thanks :)