How to open an activity from a pager adapter? - android

I currently am using this code to try and open a new activity from an activity that's part of a pager adapter that's swiping between 3 activities.
public class CustomPagerAdapter extends PagerAdapter implements OnClickListener {
private Context mContext;
public CustomPagerAdapter(Context context){
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject modelObject = ModelObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup)
inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
public void onClick(View view) {
//start new activity
Intent i = new Intent(mContext, SubjectActivity.class);
mContext.startActivity(i);
}
}
The code itself isn't throwing any errors, but when I run the app it stops the moment I click on the button. It wasn't having problems before I attempted to implement the onClick function so I am certain the problem is with how I have written that, but I can't figure out where. What is the issue with this method of opening a new activity?

Related

How to close viewAdapter with button on last image?

what I am trying to do is close the image adapter at the click of a button placed in the third view.
I am setting the views following this tutorial and it works fine: https://www.journaldev.com/10096/android-viewpager-example-tutorial
Now what I am trying to do is close the adapter with a botton in the last view. I get an error that says that points the button: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I think this is because the button is not on the main layout but on the view layout. so how can I acces it correctly to hide/close the adapter
this is the main
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView3 = findViewById(R.id.textView3);
textView3.setVisibility(View.INVISIBLE);
btnClose=findViewById(R.id.btnClose);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new CustomPagerAdapter(this));
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
viewPager.setVisibility(View.INVISIBLE);
textView3.setVisibility(View.VISIBLE);
}
});
}
This is the adapter
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject modelObject = ModelObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
This is the model object class
public enum ModelObject {
RED(R.string.red, R.layout.view_red),
BLUE(R.string.blue, R.layout.view_blue),
GREEN(R.string.green, R.layout.view_green);
private int mTitleResId;
private int mLayoutResId;
ModelObject(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
Just to know how it works I want to hide the adapter and show a textview. Again I think the problem is the button being on another layout, so how can I call it?
Implement your listener in main class & pass it to viewpager. Attach the listener on demand, only the review view.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView3 = findViewById(R.id.textView3);
textView3.setVisibility(View.INVISIBLE);
viewPager = (ViewPager) findViewById(R.id.viewpager);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
viewPager.setVisibility(View.INVISIBLE);
textView3.setVisibility(View.VISIBLE);
}
}
viewPager.setAdapter(new CustomPagerAdapter(this), listener);
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
}
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
private View.OnClickListener mListener;
public CustomPagerAdapter(Context context, View.OnClickListener listener) {
mContext = context;
mListener = listener;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject modelObject = ModelObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
if (position == 2) {
View btnClose = layout.findViewById(R.id.btnClose);
btnClose.setOnClickListener(mListener);
}
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}

What is the best place to retrive ViewPager child's layout?

Good morning,
I have a Fragment which its layout has a ViewPager, I provide a custom PageAdapter to show two child layouts. One layout is to fill with personal data and another layout is to fill with Address data by the user. On my fragment I want to retrieve both layouts data and fill a object Pessoa(Person) with an attribute Endereco (Address). So far my ViewPager is working and both layout are displayed, however when I try to get the fields on both layouts, either on onCreateView or onResume fragment's method, using :
viewpager.getChildAt(0).findViewById(R.id.txt1)
I got an NullPointerException, but if I add an OnPageChangeListener this works, I not sure if it's the best approach. Is There a best place to retrieve a reference to the viewpager child's layout?
Ps. I don't want to use two other Fragments in order to display each of the layouts.
PageAdapter
public class ViewPagerCadastroPessoaAdapter extends PagerAdapter {
private Context context;
private int[] views = {R.layout.layout_cadastro_dados_pessoais,R.layout.layout_cadastro_endereco };
public ViewPagerCadastroPessoaAdapter(Context context) {
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = LayoutInflater.from(this.context);
View layout = inflater.inflate(views[position], container, false);
container.addView(layout, position);
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Dados Pessoais";
case 1:
return "Endereço";
}
return super.getPageTitle(position);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}}
ViewPager's holder Fragment
public class CadastroPessoaFragment extends Fragment {
private ViewPager viewPagerCadastroPessoa;
private TabLayout tabLayoutCadastroPessoa;
public CadastroPessoaFragment() {
}
public static CadastroPessoaFragment newInstance() {
return new CadastroPessoaFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_cadastro_pessoa, container, false);
tabLayoutCadastroPessoa = root.findViewById(R.id.tabLayoutCadastroPessoa);
viewPagerCadastroPessoa = root.findViewById(R.id.viewPagerCadastroPessoa);
viewPagerCadastroPessoa.setOffscreenPageLimit(2);
viewPagerCadastroPessoa.setAdapter(new ViewPagerCadastroPessoaAdapter(getContext()));
tabLayoutCadastroPessoa.setupWithViewPager(viewPagerCadastroPessoa);
int cor = ContextCompat.getColor(getContext(), android.R.color.white);
tabLayoutCadastroPessoa.setTabTextColors(cor, cor);
//get a null pointer
viewPagerCadastroPessoa.getChildAt(0).findViewById(R.id.txt1);
viewPagerCadastroPessoa.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//works fine
viewPagerCadastroPessoa.getChildAt(0).findViewById(R.id.txt1);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return root;
}
#Override
public void onResume() {
super.onResume();
//get a null pointer
viewPagerCadastroPessoa.getChildAt(0).findViewById(R.id.txt1);
}
}
Thank you all in advance
UPDATE
According with
Anton Malyshev answer
The way Viewpager creates its pages is kind of "unsynchronized", so I used the following approach to solve my problem:
On my custom adapter I definied an interface with a single method onViewPagerReady(), as my Viewpager will always have only two pages, inside instantiateItem I check when position is 1 (once position starts with 0), if position == 1 I call the method onViewPagerReady that my fragment viewpager's holder implements, so inside this method I retrieve the layout of viewpager's children
public class ViewPagerCadastroPessoaAdapter extends PagerAdapter {
public interface ViewPagerObserver{
void onViewPagerReady();
}
private Context context;
private int[] views = {R.layout.layout_cadastro_dados_pessoais,R.layout.layout_cadastro_endereco };
private ViewPagerObserver observer;
public ViewPagerCadastroPessoaAdapter(Context context, ViewPagerObserver observer) {
this.context = context;
this.observer = observer;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = LayoutInflater.from(this.context);
View layout = inflater.inflate(views[position], container, false);
container.addView(layout, position);
if(position == 1){
observer.onViewPagerReady();
}
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Dados Pessoais";
case 1:
return "Endereço";
}
return super.getPageTitle(position);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
Fragment Viewpager's Holder
#Override
public void onViewPagerReady() {
View rootCadastroDadosPessoais = viewPagerCadastroPessoa.getChildAt(0);
View rootCadastroEnderecos =viewPagerCadastroPessoa.getChildAt(1);
}
Thank you all.
Just wait until viewPagerCadastroPessoa.getChildCount() will be greater than 0. The pages in ViewPager are not created yet in onResume (they are created asynchronously).

ViewPager extending PagerAdapter is not able to set view

My code for this class is unable to show view at the 0th position and is also showing irrelevant data sometime. This view pager is attached with a tablayout.
I want to know why this is happening and if there is some other way to handle viewpager extending PagerAdapter.I will be happy if I will come to know about some another class relevant to PagerAdapter but without using Fragment.
public class JobcardListViewPagerAdapter extends PagerAdapter implements IWebServiceAdapter {
Context mContext;
LayoutInflater mLayoutInflater;
List<TabLayoutDetails> tabLayoutDetailsList;
ActiveJobCardListResponse activeJobCardListResponse;
Activity activity;
View itemView;
WebService webService;
public JobcardListViewPagerAdapter(Context context, List<TabLayoutDetails> tabLayoutDetailsList) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.tabLayoutDetailsList = tabLayoutDetailsList;
webService = new WebService();
}
public JobcardListViewPagerAdapter() {
}
#Override
public int getCount() {
return tabLayoutDetailsList.size(); // value of tabLayoutDetailsList.size() returning 10;
}
#Override
public CharSequence getPageTitle(int position) {
return tabLayoutDetailsList.get(position).getDescription();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
itemView = mLayoutInflater.inflate(R.layout.active_job_card_list_view_pager_adapter, container, false);
GetActiveJobCardList(position);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}

Android - ViewPager flipping just Layouts instead of Fragments

Is there a simple way on Android how to flip between different layouts without the need of using fragments. My views are static (nothing really happens there) but for localization purposes we won't be using images so I would go for layout solution.
I would be grateful for a good example showing this technique.
EDIT:
Here is fully working code based on the answer below:
public class LayoutPagerAdapter : PagerAdapter
{
Context m_context;
readonly int[] m_slideLayoutResourceIds;
public LayoutPagerAdapter(Context context, int[] slideLayoutResourceIds)
{
m_context = context;
m_slideLayoutResourceIds = slideLayoutResourceIds;
}
public override Java.Lang.Object InstantiateItem(ViewGroup container, int position)
{
var inflater = LayoutInflater.From(m_context);
var view = inflater.Inflate(m_slideLayoutResourceIds[position], container, false);
container.AddView(view);
return view;
}
public override void DestroyItem(View container, int position, Java.Lang.Object objectValue)
{
base.DestroyItem(container, position, objectValue);
}
#region implemented abstract members of PagerAdapter
public override bool IsViewFromObject(View view, Java.Lang.Object objectValue)
{
return view == objectValue;
}
public override int Count
{
get
{
return m_slideLayoutResourceIds.Length;
}
}
#endregion
}
You can create your own simple adapter for that:
public static class ViewPagerAdapter extends PagerAdapter {
private Context mContext;
public ViewPagerAdapter(Context context) {
mContext = context;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
View view = LayoutInflater.from(mContext).inflate(R.layout.your_layout, container, false);
return view;
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}

How do I access my Views when using ViewPager/PagerAdapter?

Similar question Access ViewPager views from onCreate?
I created a ViewPager where different layout can moves around. One layout has a button. My question is if a user click on this button, he will move another page. How to achieve it. Here is the viewpager adapter class:
public class SwipeAdapter extends PagerAdapter {
private LayoutInflater mInflater;
private static int[] mLayouts = { R.layout.view_layout1,
R.layout.view_layout2, R.layout.view_layout3, R.layout.view_layout4 };
SwipeAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ViewGroup pageView= (ViewGroup) mInflater.inflate(mLayouts[position],
container, false);
container.addView(pageView);
getItemPosition(pageView);
return pageView;
}
/**
* #return the mCurrentposition
*/
#Override
public int getCount() {
return mLayouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
}

Categories

Resources