I'm a little desperate with viewpagers / different layouts shown in them.
Summarized: Switching through different layouts works perfectly. Now I want to implement buttons / functionality on the different layouts, which doesn't work.
I have the following viewpager which functions well. It iterates through the layouts-list and shows the different layouts.
My Activity
public static final String LOG_TAG = MainActivity.class.getSimpleName();
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_swipe);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
//btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
layouts = new int[] {
R.layout.activity_mmg_description_start,
R.layout.activity_mmg_question_1,
R.layout.activity_mmg_question_2,
R.layout.activity_mmg_question_3,
R.layout.activity_mmg_question_4,
R.layout.activity_mmg_question_5,
R.layout.activity_mmg_question_6,
R.layout.activity_mmg_question_7,
R.layout.activity_mmg_question_8,
R.layout.activity_mmg_question_9,
R.layout.activity_mmg_question_10,
R.layout.activity_mmg_question_11,
R.layout.activity_mmg_question_12,
R.layout.activity_mmg_question_13,
R.layout.activity_mmg_question_14
};
// adding bottom dots
addBottomDots(0);
viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
#
Override
public void onBackPressed() {}
public void btnNextClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#
Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start_measurement_manual));
//btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
//btnSkip.setVisibility(View.VISIBLE);
}
}
#
Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#
Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(getResources().getColor(R.color.dot_inactive));
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(getResources().getColor(R.color.dot_active));
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
startActivity(new Intent(this, ManualActivity.class));
finish();
}
public class ViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public ViewPagerAdapter() {
}
#
Override
public Object instantiateItem(ViewGroup container, int position) {
//Inflate the correct layout
layoutInflater = (LayoutInflater) getSystemServ**Option 1: starting with layout activity_mmg_question_1**ice(Context.LAYOUT_INFLATER_SERVICE);
//layouts[] is an int[] that points to resources such as R.layout.start_page
View inflatedView = layoutInflater.inflate(layouts[position], container, false);
((ViewPager) container).addView(inflatedView, 0);
switch (position) {
case R.layout.activity_mmg_description_start:
Log.d(LOG_TAG, "QD " + "Firstviewcame");
case R.layout.activity_mmg_question_1:
//LinearLayout linearLayout_mmg_1 = (LinearLayout)inflatedView.findViewById(R.id.linearlayout_mmg_1);
Button testButton = (Button) findViewById(R.id.testbutton);
testButton.setOnClickListener(new View.OnClickListener() {
#
Override
public void onClick(View v) {
Log.d(LOG_TAG, "QD " + "Swipebuttonclicked");
}
});
}
return inflatedView;
}
#
Override
public int getCount() {
return layouts.length;
}
#
Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#
Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
I want to add functionality to the different layouts. On layout: activity_mmg_question_1 is a button (R.id.testbutton) which should write a log message.
I've tried a few options.
Option 1: starting with layout activity_mmg_question_1
Outcommenting the R.layout.activity_mmg_description_start at the beginning:
layouts = new int[]{
//R.layout.activity_mmg_description_start,
R.layout.activity_mmg_question_1,
The following code works:
#Override
public Object instantiateItem(ViewGroup container, int position) {
//Inflate the correct layout
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//layouts[] is an int[] that points to resources such as R.layout.start_page
View inflatedView = layoutInflater.inflate(layouts[position], container, false);
((ViewPager)container).addView(inflatedView,0);
LinearLayout linearLayout_mmg_1 = (LinearLayout)inflatedView.findViewById(R.id.linearlayout_mmg_1);
Button testButton = (Button)findViewById(R.id.testbutton);
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d (LOG_TAG, "QD " + "Swipebuttonclicked");
}
});
return inflatedView;
}
Quite understandable: It inflates the layout, finds the button, works.
Option 2: starting with layout activity_mmg_description_start
Starting with R.layout.activity_mmg_description_start at the beginning:
layouts = new int[]{
R.layout.activity_mmg_description_start,
R.layout.activity_mmg_question_1,
It ends up with a
FATAL EXCEPTION: main
[...]
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I think I also got this: on the first layout (R.layout.activity_mmg_description_start) it doesn't find the button, so it points to null, and the error shows up.
How to prevent this? That led me to the idea of:
Option 3: switch-case
Displaying of the different layouts works, but the log-message from the button doesn't work.
#Override
public Object instantiateItem(ViewGroup container, int position) {
//Inflate the correct layout
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//layouts[] is an int[] that points to resources such as R.layout.start_page
View inflatedView = layoutInflater.inflate(layouts[position], container, false);
((ViewPager)container).addView(inflatedView,0);
switch (position){
case R.layout.activity_mmg_description_start:
Log.d (LOG_TAG, "QD " + "Firstviewcame");
case R.layout.activity_mmg_question_1:
//LinearLayout linearLayout_mmg_1 = (LinearLayout)inflatedView.findViewById(R.id.linearlayout_mmg_1);
Button testButton = (Button)findViewById(R.id.testbutton);
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d (LOG_TAG, "QD " + "Swipebuttonclicked");
}
});
}
return inflatedView;
}
Does anybody have an idea or solution?
Best and thanks in advance,
tigercode
I think you should use Fragments.
Try to setOnClickListener before call ((ViewPager)container).addView(inflatedView,0);
public Object instantiateItem(ViewGroup container, int position) {
//Inflate the correct layout
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//layouts[] is an int[] that points to resources such as R.layout.start_page
View inflatedView = layoutInflater.inflate(layouts[position], container, false);
switch (position){
case R.layout.activity_mmg_description_start:
Log.d (LOG_TAG, "QD " + "Firstviewcame");
case R.layout.activity_mmg_question_1:
//LinearLayout linearLayout_mmg_1 = (LinearLayout)inflatedView.findViewById(R.id.linearlayout_mmg_1);
Button testButton = (Button)findViewById(R.id.testbutton);
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d (LOG_TAG, "QD " + "Swipebuttonclicked");
}
});
}
((ViewPager)container).addView(inflatedView,0);
return inflatedView;
}
Related
I am making an app that contains a small questionnaire for users asking them about their food preferences. To achieve this, I am trying to create a ViewPager whose layout contains Radiobuttons inside a Radiogroup. I would like my View pager to move to the next page when the user selects a radio button. I am unable to get this to work. I couldn't find anything similar to this on Google.
Pager Adapter:
public class SliderAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
int position;
RadioGroup radioGroup;
ImageView imageView;
TextView textView;
RadioButton one, two, three;
// SharedPreferences sharedPreferences;
public SliderAdapter(Context context) {
this.context = context;
position = 0;
}
int[] images = {R.drawable.meat_preferences,
R.drawable.dairy_preferences,
R.drawable.spices_preferences};
int[] questions = {R.string.onboarding_2, R.string.onboarding_3, R.string.onboarding_4};
int[][] answers = {{R.string.onboarding_2_1, R.string.onboarding_2_2, R.string.onboarding_2_3},
{R.string.onboarding_3_1, R.string.onboarding_3_2, R.string.onboarding_3_3},
{R.string.onboarding_4_1, R.string.onboarding_4_2, R.string.onboarding_4_3}};
#Override
public int getCount() {
return questions.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.onboarding_slides_layout, container, false);
imageView = view.findViewById(R.id.slide_image);
textView = view.findViewById(R.id.questions);
radioGroup = view.findViewById(R.id.radio_group);
// view.setTag("Radio" + position);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radio_button = group.findViewById(checkedId);
Toast.makeText(context, radio_button.getText(), Toast.LENGTH_SHORT)
.show();
}
});
imageView.setImageResource(images[position]);
textView.setText(questions[position]);
for (int i = 0; i < radioGroup.getChildCount(); i++) {
((RadioButton) radioGroup.getChildAt(i)).setText(answers[position][i]);
}
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout)object);
}
}
Onboarding class which is called from the main activity:
public class Onboarding extends AppCompatActivity {
ViewPager viewPager;
LinearLayout linearLayout;
ImageView zero, one, two;
ImageView[] imageViews;
Button button;
SliderAdapter pagerAdapter;
RadioGroup radioGroup;
RadioButton option_1, option_2, option_3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onboarding);
viewPager = findViewById(R.id.slider);
linearLayout = findViewById(R.id.dots);
button = findViewById(R.id.next_btn);
zero = findViewById(R.id.intro_indicator_1);
one = findViewById(R.id.intro_indicator_2);
two = findViewById(R.id.intro_indicator_3);
imageViews = new ImageView[]{zero, one, two};
//call adapter
pagerAdapter = new SliderAdapter(this);
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#SuppressLint("UseCompatTextViewDrawableApis")
#Override
public void onPageSelected(int position) {
updateIndicators(position);
if (position == 2){
button.setVisibility(View.VISIBLE);
button.setCompoundDrawableTintList(ColorStateList.valueOf(Color.parseColor("#4D000000")));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
void updateIndicators(int position) {
for (int i = 0; i < imageViews.length; i++) {
imageViews[i].setBackgroundResource(
i == position ? R.drawable.indicator_selected : R.drawable.indicator_unselected
);
}
}
}
How do I get the radiogroup selections in the "Onboarding" class?
just call this
mRadioGroup.check(mRadioGroup.getChildAt(0).getId());
after
mViewPager.setCurrentItem(0);
I have implemented a ViewPager in my application which consist of two slides. I can go from first slide to second slide and reverse as well. But I have a special case here. If the user goes from First Slide to Second Slide. He should not be able to go back to the First slide. I need to disable going back to the First Slide once he enters the Second Slide.
Here is my code:
public class BotConnectionDialog extends DialogFragment {
private RelativeLayout toolbar;
private ImageView toolbarCloseButton;
private View layoutView;
private ViewPager viewPager;
private BotConnectionDialogAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
int width, height;
DisplayMetrics metrics;
private int[] layouts;
private final String TAG = BotConnectionDialog.class.getSimpleName();
private Button btnSkip, btnNext;
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
getActivity().getSupportFragmentManager().popBackStackImmediate();
}
});
}
};
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.botconnection_layout, container, false);
Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/corbert.otf");
toolbar = (RelativeLayout) rootView.findViewById(R.id.customAppBarLayout);
toolbar.setBackgroundColor(Color.parseColor("#00000000"));
toolbarCloseButton = (ImageView) rootView.findViewById(R.id.toolbarCloseButton);
toolbarCloseButton.setOnClickListener(myListener);
viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) rootView.findViewById(R.id.layoutDots);
btnSkip = (Button) rootView.findViewById(R.id.btn_skip);
btnSkip.setTypeface(typeface);
btnNext = (Button) rootView.findViewById(R.id.btn_next);
btnNext.setTypeface(typeface);
metrics = getResources().getDisplayMetrics();
width = metrics.widthPixels;
height = metrics.heightPixels;
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.slide1,
R.layout.slide2};
// adding bottom dots
addBottomDots(0);
myViewPagerAdapter = new BotConnectionDialogAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
}
}
});
return rootView;
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(getActivity());
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
btnSkip.setVisibility(View.GONE);
/**
* bluetooth connection the bot
*/
Toast.makeText(getActivity(), "Finished", Toast.LENGTH_SHORT).show();
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
/**
* First page
*/
Toast.makeText(getActivity(), "2nd page", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
//dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Override
public void onResume() {
super.onResume();
// getDialog().getWindow().setLayout((7 * width) / 7, (4 * height) / 5);
}
public class BotConnectionDialogAdapter extends PagerAdapter {
/**
* View pager adapter
*/
private LayoutInflater layoutInflater;
public BotConnectionDialogAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
/**
* To disable and enable scrolling on ViewPager, just set shouldScroll to true or false.
*/
public class ScrollableViewPager extends ViewPager {
private boolean shouldScroll = true;
public ScrollableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setShouldScroll(boolean shouldScroll) {
this.shouldScroll = shouldScroll;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
return shouldScroll && super.onTouchEvent(ev);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return shouldScroll && super.onInterceptTouchEvent(ev);
}
}
Now use this ScrollableViewPager in place of the default ViewPager and in your onPageSelected() callback
check for the position. If it is the last position, call the setShouldScroll(false) method on your viewPager instance, which will make shouldScroll to false in our ScrollableViewPager class and eventually make the scrolling invalid as we have overridden onTouchEvent() and onInterceptTouchEvent() method, which checks for the value of shouldScroll.
I am using Memory analyzer tool to detect posssible memory leak in my application and below is the image of heap profile which is saying i have 5 object of IntroActivity below is my code for introactivity i am not able to find from where this objects are created multiple times
public class IntroActivity extends AppCompatActivity {
[![enter image description here][1]][1]
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter=new MyViewPagerAdapter();
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Context context;
private Button btnSkip, btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
context=IntroActivity.this;
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.intro_layout);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.intro_first_screen,
R.layout.intro_second_screen,
R.layout.intro_third_screen,
R.layout.intro_fourth_screen,
R.layout.intro_fifth_screen,
R.layout.intro_sixth_screen,
R.layout.intro_seventh_screen,
R.layout.intro_eighth_screen};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
finish();
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(context.getResources().getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
can anyone please help in find possible leak any help is appriciated
No, you did not have 5 objects of IntroActivity.
Heap profile says there are one instance of IntroActivity and 4 instances that is inner class of IntroActivity.
Inner classes are below including anonymous class.
btnNext.setOnClickListener(new View.OnClickListener() {
...
}
btnNext.setOnClickListener(new View.OnClickListener() {
...
}
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
...
}
public class MyViewPagerAdapter extends PagerAdapter {
...
}
Use LeakCanary to detect memory leaks.
https://github.com/square/leakcanary
One of my layouts inside of my ViewPager has a button. "R.layout.add_site". I would like the option of hitting the button and it scroll to the specific page for me. I already have the option to swipe to the specific page, but I would like to have both.
Now I'm sure there's a way to do that, but for some reason, I cannot figure it out.
You'll see that I've made an attempt , but just dont know what method to call in order to make it scroll to the desired page. Which is R.layout.main.
Here's my code.
public class fieldsActivity extends Activity {
Button addSiteButton;
Button cancelButton;
Button signInButton;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// to create a custom title bar for activity window
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.fields);
// use custom layout title bar
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.topbar);
Pager adapter = new Pager();
ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);
mPager.setAdapter(adapter);
mPager.setCurrentItem(1);
addSiteButton = (Button) findViewById(R.id.addSiteButton);
addSiteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Don't know what method to call!?
}
});
cancelButton = (Button) findViewById(R.id.cancel_button);
signInButton = (Button) findViewById(R.id.sign_in_button);
}
private class Pager extends PagerAdapter {
public int getCount() {
return 3;
}
#Override
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.field01;
break;
case 1:
resId = R.layout.add_site;
break;
case 2:
resId = R.layout.main;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
}
Any help is appreciated!
call :
mPager.setCurrentItem(2);
in your onClick() method, or for a smoother scroll:
mPager.setCurrentItem(2, true);
I can't really answer WHY exactly this happens, but if you delay the setCurrentItem call for a few milliseconds it should work. My guess is that because during onResume there hasn't been a rendering pass yet, and the ViewPager needs one or something like that.
private ViewPager viewPager;
#Override
public void onResume() {
final int pos = 3;
viewPager.postDelayed(new Runnable() {
#Override
public void run() {
viewPager.setCurrentItem(pos);
}
}, 100);
}
Original Answer: here
I'm new to this android and java.
My viewpager now can slide all my xml layout, but i don't know how to access item in them.
I tried using Button mybutton = (Button) findViewById (R.layout.result), then set the onClickListener in mybutton, but then it was forced to close every time I run it.
Here is my code:
public class main extends Activity {
private ViewPager myviewpager;
private ViewPagerAdapter myviewpageradapter;
private static int NUM_AWESOME_VIEWS = 12;
Button button_1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myviewpageradapter = new ViewPagerAdapter();
myviewpager = (ViewPager) findViewById(R.id.myviewpager);
myviewpager.setAdapter(myviewpageradapter);
button_1 = (Button) myviewpager.findViewById(R.id.first_button);
button_1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
private class ViewPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return NUM_AWESOME_VIEWS;
}
#Override
public Object instantiateItem(View collection, int position) {
LayoutInflater layoutinflater = getLayoutInflater();
View view;
view = layoutinflater.inflate(R.layout.page1, null);
switch (position)
{
case 0 : view = layoutinflater.inflate(R.layout.page1, null); break;
case 1 : view = layoutinflater.inflate(R.layout.page2, null); break;
case 2 : view = layoutinflater.inflate(R.layout.page3, null); break;
case 3 : view = layoutinflater.inflate(R.layout.page4, null); break;
case 4 : view = layoutinflater.inflate(R.layout.page5, null); break;
case 5 : view = layoutinflater.inflate(R.layout.page6, null); break;
case 6 : view = layoutinflater.inflate(R.layout.page7, null); break;
case 7 : view = layoutinflater.inflate(R.layout.page8, null); break;
case 8 : view = layoutinflater.inflate(R.layout.page9, null); break;
case 9 : view = layoutinflater.inflate(R.layout.page10, null); break;
case 10 : view = layoutinflater.inflate(R.layout.page11, null); break;
case 11 : view = layoutinflater.inflate(R.layout.result, null);break;
}
((ViewPager) collection).addView(view,0);
return view;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==((View)object);
}
#Override
public void finishUpdate(View arg0) {}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View arg0) {}
}
It may just be the Problem, that your items are not found probably so try this(If your view is no LinearLayout change it)
LayoutInflater getView = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout view1 =(LineaLayout)getView.inflate(R.layout.your_view,null);
But Your Button may throw Exception furthermore there is an onClickListener set to it.
If it's just the Button define it in XML:
android:onClick"buttonClick"
then in Code
public void buttonClick(View v){
// do something
}
If this is not possible because you need to reference the Button later, I stuck with the same Problem and would like to know how it works.
I think the problem here is that you are trying to find a view (findViewById) that wasn't instatiated (inflated) yet. Try to set the button listener inside the instatiateItem method of ViewPagerAdapter type.
Example:
switch(position){
case 0 :
view = layoutinflater.inflate(R.layout.page1, null);
button_1 = (Button) view.findViewById(R.id.first_button);
button_1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
break;
(...)
}