i have problem with using Butterknife libray. There is I have SearchActivity.class use ViewPager with 3 Fragment in FragmentSearchAdapter:
SearchActivity.class
mAdapter = new FragmentSearchAdapter(getSupportFragmentManager(), SearchActivity.this);
mAdapter.addFragment("search histori");
mAdapter.addFragment("search query");
mAdapter.addFragment("search result");
mPager.setAdapter(mAdapter);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageSelected(int currentIndex) {
if(currentIndex==2) {
SearchResultFragment SearchResultFragment = (SearchResultFragment) mAdapter.getItem(2);
if (SearchResultFragment != null) {
SearchResultFragment.setDescription("Text 1","Text 2");
}
}
}
public void onPageScrolled(int arg0, float arg1, int arg2) { }
public void onPageScrollStateChanged(int arg0) { }
});
FragmentSearchAdapter.class
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
SearchHistoryFragment search_histori = new SearchHistoryFragment();
return search_histori;
case 1:
SearchQueryFragment search_query = new SearchQueryFragment();
return search_query;
case 2:
SearchResultFragment search_result = new SearchResultFragment();
return search_result;
}
return null;
}
Where one fragment is SearchResultFragment.Class
public class SearchResultFragment extends Fragment {
#Bind(R.id.text1)
TextView text1;
#Bind(R.id.text2)
TextView text2;
private String page_index;
private PageAlquranActivity activity;
public SearchResultFragment() {
}
public static SearchResultFragment newInstance(int page_index) {
SearchResultFragment fragment = new SearchResultFragment();
Bundle args = new Bundle();
args.putString(Variabel.page_index, String.valueOf(page_index));
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
page_index = getArguments().getString(Variabel.page_index);
}
activity = (PageAlquranActivity) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_search_result, container, false);
ButterKnife.bind(this, v);
return v;
}
public void setDescription(String s1, String s2) {
text1.setText(s1);
text2.setText(s2);
}
#Override
public void onAttach(Context context) {super.onAttach(context);}
#Override
public void onDetach() {
super.onDetach();
}
}
My Problem : when call method SearchResultFragment.setDescription("Text 1","Text 2"); from SearchActivity, I get error :
null object reference
each TextView. This error if use ButterKnife,but if not, it's work if I declare View like this :
text1 = rootView.findViewById(R.id.text1);
text2 = rootView.findViewById(R.id.text2);
in onCreateView.
so how to solve it ? Sorry for my English. Thanks.
#AmayDiam you need to bind ButterKnife again in the called method. Pass along the dependency for the bind - the fragment view from the OnPageChangeListener
SearchActivity.class
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageSelected(int currentIndex)
{
if(currentIndex==2)
{
SearchResultFragment SearchResultFragment = (SearchResultFragment) mAdapter.getItem(2);
if (SearchResultFragment != null)
{
SearchResultFragment.setDescription(mPager.getChildAt(currentIndex)"Text 1","Text 2");
}
}
}
public void onPageScrolled(int arg0, float arg1, int arg2) { }
public void onPageScrollStateChanged(int arg0) { }
});
SearchResultFragment.Class
public void setDescription(View view,String s1, String s2)
{
ButterKnife.bind(this, view);
//
text1.setText(s1);
text2.setText(s2);
}
Had similar issue too, just because I've added butterknife from Android Studio's Dependency management and not by copy-pasting gradle lines from Butterknife website.
So I had to add
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
instead of just
compile 'com.jakewharton:butterknife:8.5.1'
Related
I want to create a multi-step registration form in my android app. I wish to use the viewpager with multiple fragments and each fragment being a step in a registration.
At the end, I want to submit all the data submitted in each fragment using an activity to a mysql database. Can I get a small sample code for this?
This is what I have tried so far. I am able to implement a viewpager with multiple fragments. I have created an interface in the StepOne.java Fragment so as to communicate to an activity. But I am not able to retrieve data from these fragments. It throws a null-pointer exception on line 52.
Here is my code:
SliderActivity.java:
public class SliderActivity extends AppCompatActivity {
ViewPager viewPager;
EditText edName,edPassword, edConfPass;
TextView tvShowAll;
ViewPagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slider);
viewPager = findViewById(R.id.view_pager);
mPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mPagerAdapter);
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) {
}
});
}
public void selectIndex(int newIndex) {
viewPager.setCurrentItem(newIndex);
}
#Override
public void onBackPressed() {
int currentPosition = viewPager.getCurrentItem();
if (currentPosition != 0) {
viewPager.setCurrentItem(viewPager.getCurrentItem()-1);
} else {
super.onBackPressed();
}
}
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new StepOne();
case 1:
return new StepTwo();
case 2:
return new StepThree();
}
return null;
}
#Override
public int getCount() {
return 3; //three fragments
}
}
}
StepOne.java:
public class StepOne extends Fragment {
Button buttonInFragment1;
EditText edName;
public interface ActivityFragmentCallback {
void onSetName(String name);
}
ActivityFragmentCallback listener;
public StepOne() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_step_one, container, false);
edName = rootView.findViewById(R.id.edName);
buttonInFragment1 = rootView.findViewById(R.id.button_one);
if(buttonInFragment1 != null) {
buttonInFragment1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(),edName.getText().toString(),Toast.LENGTH_SHORT).show();
if(edName != null) {
listener.onSetName(edName.getText().toString());
}
switch (view.getId()){
case R.id.button_one:
((SliderActivity)getActivity()).selectIndex(1);
break;
}
}
});
}
return rootView;
}
#Override
public void onAttach(Context context){
super.onAttach(context);
try {
listener = (ActivityFragmentCallback)context;
}catch (ClassCastException c){
c.printStackTrace();
}
}
}
MessageActivity.java: Here is where I need all the data submitted from all the fragments
public class MessageActivity extends AppCompatActivity implements StepOne.ActivityFragmentCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
}
#Override
public void onSetName(String name){
// tvShowAll = findViewById(R.id.tvShowAll);
// tvShowAll.setText(name);
Toast.makeText(getApplicationContext(),name, Toast.LENGTH_LONG).show();
}
}
Below is some reference link for step by step registration;
Hope you have help
https://github.com/stepstone-tech/android-material-stepper
https://github.com/baoyachi/StepView?utm_source=android-arsenal.com&utm_medium=referral&utm_campaign=3774
I am working on a simple implementation of ViewPager in android but everytime I swap my screen addOnPageChangeListener works fine but I see unusual values in my logs inside getItem of my FragmentStatePagerAdapter . and my page swaps but I am unable to change fragment into it. and inside my fragment Slider val (log value) remains same and it hits to zero so each-time when Viewpager is swapped i get the same result.
Activity:
public class OnBoardingActivity extends AppCompatActivity {
.....
.....
static final int ITEMS = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_on_boarding);
ButterKnife.bind(this);
StatusBarUtil.setTransparent(this);
StatusBarUtil.setLightMode(this);
initPager();
}
private void initPager() {
sliderAdapter = new SliderAdapter(getSupportFragmentManager());
if(sliderAdapter!=null){
onboard_pager.setAdapter(sliderAdapter);
}
onboard_pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(position==0){
indicators.setImageResource(R.drawable.step1_dots);
}
else if(position==1){
indicators.setImageResource(R.drawable.step2_dots);
}else if(position==2){
indicators.setImageResource(R.drawable.step3_dots);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public static class SliderAdapter extends FragmentStatePagerAdapter {
public SliderAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
Log.d("OnBoarding","position "+position);
return OnBoardingSlider.newInstance(position);
}
#Override
public int getCount() {
return ITEMS;
}
}
}
Fragment:
public class OnBoardingSlider extends Fragment {
View mView;
int index;
ImageView img;
TextView head_text,sub_head_text;
public static OnBoardingSlider newInstance(int index){
OnBoardingSlider f = new OnBoardingSlider();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.frag_on_boarding_page,container,false);
return mView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
img = mView.findViewById(R.id.onboard_pager_img);
head_text = mView.findViewById(R.id.head_text);
sub_head_text = mView.findViewById(R.id.sub_head_text);
super.onViewCreated(view, savedInstanceState);
switch (index){
case 0:
Log.d("Slider val",""+index);
img.setImageResource(R.drawable.purpleimage_slider);
head_text.setText(getString(R.string.ask));
sub_head_text.setText(getString(R.string.ask_sub_head));
head_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.purple_head));
sub_head_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.purple_head_sub));
break;
case 1:
Log.d("Slider val",""+index);
img.setImageResource(R.drawable.blueimage_slider);
head_text.setText(getString(R.string.ask));
sub_head_text.setText(getString(R.string.ask_sub_head));
head_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.blue_head));
sub_head_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.blue_head_sub));
break;
case 2:
Log.d("Slider val",""+index);
img.setImageResource(R.drawable.greenimage_slider);
head_text.setText(getString(R.string.ask));
sub_head_text.setText(getString(R.string.ask_sub_head));
head_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.green_head));
sub_head_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.green_head_sub));
break;
default:
Log.d("Slider val",""+index);
img.setImageResource(R.drawable.purpleimage_slider);
head_text.setText(getString(R.string.ask));
sub_head_text.setText(getString(R.string.ask_sub_head));
head_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.purple_head));
sub_head_text.setTextColor(ContextCompat.getColor(getActivity(),R.color.purple_head_sub));
}
}
}
You are not getting the arguments after setting them. so
in onCreate
Bundle bundle=getArguments();
index = bundle.getInt("index");
The fragment consists of View Pager which shows the product count that
needs to be updated when the product is deleted or added .
public class SubCategoryFragment extends BaseFragment implements OnItemClickListener
{
private View rootView;
private MasterCategory subCategory;
private RecyclerView subCategoryRecyclerView;
private SubCategoryListAdapter subCategoryListAdapter;
private ArrayList<MasterCategory> superSubCategories;
private String iconImageURL;
private ArrayList<MerchantOrder> merchantorder;
/*private IRequestComplete iRequestComplete;*/
private int categoryId;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
return rootView = inflater.inflate(R.layout.fragment_category_list, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
initialiseUI();
}
initialise fragment
protected void initialiseUI()
{
categoryId = getArguments().getInt("categoryId");
iconImageURL = (String) getArguments().getSerializable("iconImageURL");
subCategory = (MasterCategory) getArguments().getSerializable("data");
subCategoryRecyclerView = (RecyclerView) rootView.findViewById(R.id.category_list_rc_view);
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
subCategoryRecyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(context);
subCategoryRecyclerView.setLayoutManager(mLayoutManager);
superSubCategories = subCategory.getCategories();
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
if (superSubCategories != null && !superSubCategories.isEmpty())
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories, iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
subCategoryListAdapter.setmOnItemClickListener(this);
updateListView();
}
else
{
rootView.findViewById(R.id.text_no_order_error).setVisibility(View.VISIBLE);
((TextView) rootView.findViewById(R.id.text_no_order_error)).setText("No Category found!");
}
}
Update the listview
private void updateListView()
{
if (subCategoryListAdapter == null)
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories,iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
}
else
{
subCategoryListAdapter.notifyDataSetChanged();
}
subCategoryListAdapter.notifyDataSetChanged();
}
the itemclick opens up a fragment which displays the product details
#Override
public void onItemClick(View view, int position)
{
/*MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryProductsFragment superSubCategoryProductsFragment = new SuperSubCategoryProductsFragment();
superSubCategoryProductsFragment.setArguments(bundle);
manageFragment(superSubCategoryProductsFragment, SuperSubCategoryProductsFragment.class.getName(), CategoryDetailsFragment.class.getName(), bundle);*/
/*ArrayList<MasterCategory> superSubCategories = subCategoryListAdapter.getSuperSubCategory(position).getCategories();
if (null != superSubCategories){
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryListFragment categoryDetailsFragment = new SuperSubCategoryListFragment();
categoryDetailsFragment.setArguments(bundle);
manageFragment(categoryDetailsFragment, SuperSubCategoryListFragment.class.getName(), SubCategoryFragment.class.getName(), null);
}*/
MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
superSubCategories.getSubCategoryCount();
superSubCategories.getProductCount();
subCategoryListAdapter.notifyDataSetChanged();
if (superSubCategories.isHasChildCategory())
{
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
Intent intent = new Intent(context, BaseFragmentActivity.class);
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SuperSubCategoryFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
else
{
Intent intent = new Intent(context, BaseFragmentActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("categoryId", superSubCategories.getCategoryId());
bundle.putString("categoryName", superSubCategories.getName());
bundle.putBoolean("isSubCatProducts", !superSubCategories.isHasChildCategory());
bundle.putInt("ProductCount", superSubCategories.getProductCount());
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SubCategoryProductsFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView)
{
super.onAttachedToRecyclerView(subCategoryRecyclerView);
subCategoryRecyclerView.getAdapter().notifyDataSetChanged();
}
}
This is my Adapter attached to the fragment
public class SubCategoryListAdapter extends RecyclerView.Adapter<SubCategoryListAdapter.ViewHolder> implements View.OnClickListener {
private static final String TAG = SubCategoryListAdapter.class.getSimpleName();
private ArrayList<MasterCategory> superSubCategories;
private ImageLoader imageloader;
private com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener;
private String iconImageURL;
#Override
public void onClick(View view)
{
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(view, (Integer) view.getTag());
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView name;
public TextView productCount;
public NetworkImageView image;
public ViewHolder(View itemLayoutView)
{
super(itemLayoutView);
productCount = (TextView) itemLayoutView.findViewById(R.id.product_count);
name = (TextView) itemLayoutView.findViewById(R.id.name);
image = (NetworkImageView) itemLayoutView.findViewById(R.id.image);
}
}
public SubCategoryListAdapter(ArrayList<MasterCategory> superSubCategories, String iconImageURL)
{
this.superSubCategories = superSubCategories;
imageloader = Global.getInstance().getImageLoader();
this.iconImageURL = iconImageURL;
}
#Override
public SubCategoryListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.super_category_list_row, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position)
{
holder.name.setText("" + superSubCategories.get(position).getName());
holder.image.setDefaultImageResId(R.drawable.logo_amoda);
holder.image.setImageUrl(iconImageURL, imageloader);
if(!superSubCategories.get(position).isHasChildCategory())
{
holder.productCount.setText("" + superSubCategories.get(position).getProductCount());
}
else
{
holder.productCount.setText("");
holder.productCount.setBackgroundResource(R.drawable.icn_right_arrow);
}
holder.itemView.setTag(position);
holder.itemView.setOnClickListener(this);
}
public void setmOnItemClickListener(com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener)
{
this.mOnItemClickListener = mOnItemClickListener;
}
#Override
public int getItemCount()
{
if (superSubCategories != null)
return superSubCategories.size();
else
return 0;
}
public MasterCategory getSuperSubCategory(int position)
{
return superSubCategories.get(position);
}
}
This is my View pager in my activity
private void showSubCategoryTabs()
{
setToolbarTitle(category != null ? category.getName() : "");
try
{
mPromotionalImage.setDefaultImageResId(R.drawable.nodeals_img);
mPromotionalImage.setImageUrl(category.getImageUrl(), imageLoader);
}
catch (Exception e)
{
e.printStackTrace();
}
tabContent = new ArrayList<String>();
for (MasterCategory subCategories : category.getCategories())
{
/*Check if the sub-sub category has super-sub category or not.*/
if (null != subCategories.getCategories())
tabContent.add(subCategories.getName());
}
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
#Override
public void onPageSelected(int position)
{
Fragment fragment = ((SectionsPagerAdapter) mViewPager.getAdapter()).getFragment(position);
if (fragment != null)
{
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter
{
private SectionsPagerAdapter sectionspageradapter;
private FragmentManager fragmentManager=null;
private Bundle bundle=new Bundle();
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
fragmentManager=fm;
}
#Override
public Object instantiateItem(ViewGroup container,int position)
{
Object obj=super.instantiateItem(container,position);
if(obj instanceof Fragment)
{
Fragment f=(Fragment)obj;
String tag=f.getTag();
f.onResume();
}
return obj;
}
#Override
public Fragment getItem(int position)
{
MasterCategory subCategories = category.getCategories().get(position);
if (subCategories.isHasChildCategory())
{
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("iconImageURL", category.getIconImageUrl());
bundle.putSerializable("data", category.getCategories().get(position));
subCategoryFragment.setArguments(bundle);
return subCategoryFragment;
}
else
{
SubCategoryProductsFragment subCategoryProductsFragment = new SubCategoryProductsFragment();
Bundle bundle = new Bundle();
bundle.putInt("categoryId", subCategories.getCategoryId());
bundle.putString("categoryName", subCategories.getName());
bundle.putBoolean("isSubCatProducts", true);
subCategoryProductsFragment.setArguments(bundle);
return subCategoryProductsFragment;
}
}
#Override
public int getCount()
{
return tabContent.size();
}
#Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
return tabContent.get(position);
}
public Fragment getFragment(int position)
{
String tag = String.valueOf(mMerchantSubCategories.get(position));
return fragmentManager.findFragmentByTag(tag);
}
}
#Override
public void onResume()
{
if (!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
super.onResume();
}
#Override
protected void onPause()
{
super.onPause();
}
#Override
public void onStop()
{
super.onStop();
//*Unregister event bus when the app goes in background*//*
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
#Override
public void onDestroy()
{
super.onDestroy();
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
public void onError(VolleyError volleyError)
{
UIHelper.stopProgressDialog(mProgressDialog);
Functions.Application.VolleyErrorCheck(this, volleyError);
}
just add this method to your viewPager adapter and your problem is solved.
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
this is override method of viewPager.
when you swipe one fragment to another it will automatically refresh page.
try this approach.. maybe its work for you..
put this code in your SubCategoryListAdepter
public void delete(int position) { //removes the row
superSubCategories.remove(position);
notifyItemRemoved(position);
}
make onClickListener to your ViewHolder:
suppose you click on your text and this row will be deleted.
#Override
public void onClick(View v) {
if(v.getId() == R.id.name){
//calls the method above to delete
delete(getAdapterPosition());
}
now you can also add data like this way.. thats working fine at runtime.. no need to refresh your page.
i'am tryning to update my view pager indicator from my fragment.
My problem is the project is structured like this:
MainActivity -> FragmentA -> FragmentStatePagerAdapter -> FragmentProduct
I've tried implementing an interface in the adapter but the adapter isn't able to catch the event, only the mainActivity is catching the event.
So the only thing i want it's to update view pager (FragmentStatePagerAdapter) from the fragment.
MainActivity:
public class ProductDetailActivity extends ActivityBase implements ProductFragment.OnFragmentInteractionListener, TabIndicatorListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void updateTabIndicator(ProductFragment productFragment) {
} }
**FragmentA - Set adapter etc etc **
public class ProductFragmentDetails extends FragmentBase {
private NavigationHelper navHelper = NavigationHelper.getInstance();
ViewPager viewPager;
PagerAdapter adapter;
TabPageIndicator indicator;
List<ProductPagerAdapter.RegisterValue> prices;
private FragmentManager fm;
ProductPagerAdapter pagerUpdater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
createDummyPrices();
View mainView = inflater.inflate(R.layout.fragment_product_details, container);
viewPager = (ViewPager) mainView.findViewById(R.id.pager);
viewPager.setVisibility(View.VISIBLE);
indicator = (TabPageIndicator) mainView.findViewById(R.id.indicator);
fm = getActivity().getSupportFragmentManager();
adapter = new ProductPagerAdapter(fm, getActivity().getApplicationContext(), indicator, prices);
viewPager.setAdapter(adapter);
indicator.setViewPager(viewPager);
indicator.setVisibility(View.VISIBLE);
return mainView;
}}
FragmentStateAdapter
public class ProductPagerAdapter extends FragmentStatePagerAdapter implements IconPagerAdapter, TabIndicatorListener {
... init vars etc etc
#Override
public void startUpdate(ViewGroup container) {
super.startUpdate(container);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
return Integer.toString(position + 1);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) { super.setPrimaryItem(container, position, object);
}
#Override
public void finishUpdate(ViewGroup container) {
super.finishUpdate(container);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return super.isViewFromObject(view, object);
}
#Override
public Parcelable saveState() {
return super.saveState();
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
super.restoreState(state, loader);
}
/**
* Get icon representing the page at {#code index} in the adapter.
*
* #param index
*/
#Override
public int getIconResId(int index) {
return prices.get(index).icon;
}
#Override
public int getCount() {
return prices.size(); //The number of items in the pagerAdapter must be equal to number of products
}
// Instantiate the fragment to display for that page
#Override
public Fragment getItem(int position) {
String productPrice = Double.toString(prices.get(position).price);
return ProductFragment.newInstance(productPrice, "OBS");
}
#Override
public void updateTabIndicator(ProductFragment productFragment) {
}
FragmentProduct
public class ProductFragment extends FragmentBase {
init some vars and fields....
Context context;
TabIndicatorListener tabIndicatorListener;
public static ProductFragment newInstance(String price, String observations) {
ProductFragment fragment = new ProductFragment();
Bundle args = new Bundle();
args.putString(ARG_PRICE, price);
args.putString(ARG_OBSERVATIONS, observations);
fragment.setArguments(args);
return fragment;
}
public ProductFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
if (getArguments() != null) {
mParamPrice = getArguments().getString(ARG_PRICE);
mParamObservation = getArguments().getString(ARG_OBSERVATIONS);
}
try {
tabIndicatorListener = (TabIndicatorListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement TabIndicatorListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View productView = inflater.inflate(R.layout.fragment_product, container, false);
initViews(productView); //Its initialized the views..
btnAbsent.setOnClickListener(clickOnBtnAbsent);
btnValidate.setOnClickListener(clickOnBtnValidate);
editTxtPrice.setText(String.valueOf(mParamPrice));
return productView;
}
/**
* #param productView
*/
private void initViews(View productView) {
txtViewProductName = (TextView) productView.findViewById(R.id.txtViewNameProduct);
txtViewPrice = (TextView) productView.findViewById(R.id.txtViewPrice);
}
#Override
protected int getActionBarMenuRes() {
return 0;
}
#Override
protected int getMainLayoutRes() {
return 0;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public View.OnClickListener clickOnBtnAbsent = new View.OnClickListener() {
#Override
public void onClick(View v) {
tabIndicatorListener.updateTabIndicator(ProductFragment.this);
//Here is where i want to update my view pager indicator
}
};
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Uri uri);
}
First of all I'm surprised that you didn't encounter problems due to the FragmentManager you used. Instead of :
fm = getActivity().getSupportFragmentManager();
you should use the dedicated FragmentManager for nested fragments:
fm = getChildFragmentManager();
Secondly, related to the listener target you can use one of the methods of the fragment class, getParentFragment(). This method returns, for nested fragments, the container fragment:
// in ProductFragment
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mListener = ((ProductFragmentDetails) getParentFragment()).getListener();
}
In ProductFragmentDetails you'll have the method:
public (OnFragmentInteractionListener) getListener() {
return (OnFragmentInteractionListener) adapter;
}
New and working on ViewPager, and encounter some difficulties that would like you to offer some advice...
ViewPagerAdapter class
public class ViewPagerAdapter extends FragmentPagerAdapter
{
private Context _context;
public ViewPagerAdapter(Context context, FragmentManager fm)
{
super(fm);
_context=context;
}
#Override
public Fragment getItem(int position)
{
Fragment f = new Fragment();
switch(position){
case 0:
f=App_Intro.newInstance(_context);
break;
case 1:
f=LayoutTwo.newInstance(_context);
break;
}
return f;
}
#Override
public int getCount()
{
return 2;
}
}
ViewPagerStyle1Activity class
public class ViewPagerStyle1Activity extends FragmentActivity
{
private ViewPager _mViewPager;
private ViewPagerAdapter _adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpView();
setTab();
}
private void setUpView()
{
_mViewPager = (ViewPager) findViewById(R.id.viewPager);
_adapter = new ViewPagerAdapter(getApplicationContext(),getSupportFragmentManager());
_mViewPager.setAdapter(_adapter);
_mViewPager.setCurrentItem(0);
}
private void setTab()
{
_mViewPager.setOnPageChangeListener(new OnPageChangeListener()
{
#Override
public void onPageScrollStateChanged(int position) {}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}
#Override
public void onPageSelected(int position)
{
// TODO Auto-generated method stub
switch(position)
{
case 0:
findViewById(R.id.first_tab).setVisibility(View.VISIBLE);
findViewById(R.id.second_tab).setVisibility(View.INVISIBLE);
break;
case 1:
findViewById(R.id.first_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.second_tab).setVisibility(View.VISIBLE);
break;
}
}
});
}
}
App_Intro class
public class App_Intro extends Fragment
{
public static Fragment newInstance(Context context)
{
App_Intro f = new App_Intro();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.app_introduce_scroll, null);
Button calpaidBtn = (Button) findViewById(R.id.calpaidBtn); //RED UNDERLINE ERROR
calpaidBtn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent (Intent.ACTION_VIEW,
Uri.parse("https://abc.com"));
startActivity(intent);
return;
}
});
return root;
}
}
Question:
It underlines red in the App_Intro class for findViewById that "The method findViewById(int) is undefined for the type App_Intro"
How does this be solved? Actually how to put different activities into the ViewPager? Are there any examples?
Many thanks in advance!
Use the following :
root.findViewById(..)