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);
Related
I am new to Android programming, I am creating Introduction slides using View Pager and custom adaptor. I have two introduction slides and I want the third slide to be 'sign up' activity itself. With my current implementation, the third slide is just the layout of the activity and not the activity itself.
Can you suggest how to do so?
Here is my WelcomeActivity.java (I want to start LoginActivity.java)
public class WelcomeActivity extends AppCompatActivity {
Button next;
ViewPager vp;
LinearLayout layoutBars;
MyViewPAdaptor vpAdaptor;
TextView dots[];
int[] layouts;
PrefManager prfManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prfManager = new PrefManager(this);
if (!prfManager.getIsFirstTimeLaunch()) {
launchHomeScreen();
finish();
}
setContentView(R.layout.activity_welcome);
next = (Button) findViewById(R.id.btn_next);
vp = (ViewPager) findViewById(R.id.view_pager);
layoutBars = (LinearLayout) findViewById(R.id.layoutDots);
vpAdaptor = new MyViewPAdaptor();
layouts = new int[]{
R.layout.welcome_screen1,
R.layout.welcome_screen2,
R.layout.activity_login};
vp.setAdapter(vpAdaptor);
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
vp.addOnPageChangeListener(viewPagerPageChangeListener);
next.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-1) {
// move to next screen
vp.setCurrentItem(current);
} else {
launchLoginScreen();
}
}
});
}
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);
layoutBars.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]);
layoutBars.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return vp.getCurrentItem() + i;
}
private void launchHomeScreen() {
prfManager.setFirstTimeLaunch(false);
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
finish();
}
private void launchLoginScreen() {
prfManager.setFirstTimeLaunch(false);
startActivity(new Intent(WelcomeActivity.this, LoginActivity.class));
}
// 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
next.setText(getString(R.string.start));
} else {
// still pages are left
next.setText(getString(R.string.next));
}
}
#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 MyViewPAdaptor extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPAdaptor() {
}
#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);
}
}
}
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
if (position == 2)
startActivity(new Intent(this, LoginActivity.class));
}
});
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'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;
}
I've seen quite a few posts about this "issue" with RecyclerView, but I can't manage to fix it.
Every time I scroll, my custom CheckBoxes (starStyle) keep turning on/off.
I've tried to follow other solutions here on Stack, but none seems to do the job for me.
Just to explain the structure of my app, I've a long list (each item has a StarStyle CheckBox): when I click on an item, the app takes me in the Details Page for that item, where I can set the CheckBox, too. I managed to bind the list's checkbox and the one in the detail page, but I still having this annoying problem.
Here my code for the ListFragment:
public class PetrolStationListFragment extends Fragment {
private RecyclerView mPetrolStationRecyclerView;
private PetrolStationAdapter mAdapter;
private int itemPosition;
private int mLastAdapterClickPosition = -1;
private List<Boolean> mCheckState = new ArrayList<>();
public static boolean toBeCreated;
private static final String ARG_POSITION = "position";
// Design pattern to instantiate a new fragment.
public static PetrolStationListFragment newInstance(int position) {
PetrolStationListFragment fragment = new PetrolStationListFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
/********************************************************/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_petrol_station_list, container, false);
mPetrolStationRecyclerView = (RecyclerView) view.findViewById(R.id.petrol_recycler_view);
mPetrolStationRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
private void updateUI() {
PetrolStationDAO petrolStationDAO = PetrolStationDAO.get(getActivity());
List<PetrolStation> petrolStations = petrolStationDAO.getPetrolStations();
if (mAdapter == null || toBeCreated) {
mAdapter = new PetrolStationAdapter(petrolStations);
mPetrolStationRecyclerView.setAdapter(mAdapter);
toBeCreated = false;
} else {
if (mLastAdapterClickPosition < 0) {
mAdapter.setPetrolStations(petrolStations);
mAdapter.notifyDataSetChanged();
} else {
mAdapter.notifyItemChanged(mLastAdapterClickPosition);
mLastAdapterClickPosition = -1;
}
mAdapter.notifyItemChanged(itemPosition);
}
}
private class PetrolStationHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private PetrolStation mPetrolStation;
private TextView mNameTextView;
private TextView mAddressTextView;
private TextView mDistanceTextView;
private CheckBox mCheckBox;
private int mPosition;
public PetrolStationHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mNameTextView = (TextView) itemView.findViewById(R.id.list_item_station_name_text_view);
mAddressTextView = (TextView) itemView.findViewById(R.id.list_item_station_address_text_view);
mDistanceTextView = (TextView) itemView.findViewById(R.id.list_item_station_distance_text_view);
mCheckBox = (CheckBox) itemView.findViewById(R.id.checkbox);
}
public void bindPetrolStation(PetrolStation petrolStation, int position) {
mPetrolStation = petrolStation;
mNameTextView.setText(mPetrolStation.getName());
mAddressTextView.setText("Via Verdi, 19/A");
mDistanceTextView.setText("300 meters");
mPosition = position;
//mCheckBox.setChecked(mPetrolStation.isFavourite());
mCheckBox.setChecked(mCheckState.get(mPosition));
Log.d("BIND_POSITION", "position: " + mPosition + " / status: " + mCheckState.get(mPosition));
mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
boolean boxChecked = mPetrolStation.isFavourite();
Log.d("BOX_CHECKED_POSITION", "boxChecked: " + boxChecked);
if (boxChecked) {
mPetrolStation.setFavourite(false);
} else {
mPetrolStation.setFavourite(true);
}
if (boxChecked) {
mCheckState.set(mPosition, false);
} else {
mCheckState.set(mPosition, true);
}
Log.d("CHECK_POSITION", "mCheckState: " + mCheckState);
// TODO: DB connection.
// PetrolStationDAO.get(getActivity()).updateItem(mCrime);
}
});
}
#Override
public void onClick(View v) {
itemPosition = mPetrolStationRecyclerView.getChildAdapterPosition(v);
Intent intent = PetrolStationPagerActivity.newIntent(getActivity(), mPetrolStation.getId());
startActivity(intent);
}
}
private class PetrolStationAdapter extends RecyclerView.Adapter<PetrolStationHolder> {
private List<PetrolStation> mPetrolStations;
public PetrolStationAdapter(List<PetrolStation> petrolStations) {
mPetrolStations = petrolStations;
for (int i = 0; i < mPetrolStations.size(); i++) {
mCheckState.add(false);
}
}
#Override
public PetrolStationHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_item_petrol_station, parent, false);
return new PetrolStationHolder(view);
}
#Override
public void onBindViewHolder(PetrolStationHolder holder, int position) {
PetrolStation petrolStation = mPetrolStations.get(position);
holder.bindPetrolStation(petrolStation, position);
// holder.setIsRecyclable(false);
}
#Override
public int getItemCount() {
return mPetrolStations.size();
}
public void setPetrolStations(List<PetrolStation> petrolStations) {
mPetrolStations = petrolStations;
}
}
}
Here the one for the DetailsFragment:
public class PetrolStationFragment extends Fragment {
private static final String ARG_PETROL_STATION_ID = "petrol_station_id";
private PetrolStation mPetrolStation;
private TextView mInfo;
private CheckBox mCheckBox;
private static TabLayout mTabLayout;
private static ViewPager mViewPager;
private static int intItems = 2;
// Navigation Tab constants.
private static final int SELF_SERVICE_POSITION = 0;
private static final int FULL_SERVICE_POSITION = 1;
// Design pattern to instantiate a new fragment.
public static PetrolStationFragment newInstance(long petrolStationId) {
Bundle args = new Bundle();
args.putLong(ARG_PETROL_STATION_ID, petrolStationId);
PetrolStationFragment fragment = new PetrolStationFragment();
fragment.setArguments(args);
return fragment;
}
/********************************************************/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long mId = getArguments().getLong(ARG_PETROL_STATION_ID);
mPetrolStation = PetrolStationDAO.get(getActivity()).getPetrolStation(mId);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceStace) {
View view = inflater.inflate(R.layout.fragment_petrol_station, container, false);
mInfo = (TextView) view.findViewById(R.id.petrol_station);
mCheckBox = (CheckBox) view.findViewById(R.id.checkbox);
mInfo.setText(mPetrolStation.getName());
mCheckBox.setChecked(mPetrolStation.isFavourite());
// TODO: to fix.
mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isFavourite) {
mPetrolStation.setFavourite(isFavourite);
}
});
// Setup Views.
mTabLayout = (TabLayout) view.findViewById(R.id.pager_header);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
// Set an Adapter for the View Pager.
TabPagerAdapter tabPagerAdapter = new TabPagerAdapter(getChildFragmentManager());
mViewPager.setAdapter(tabPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(SELF_SERVICE_POSITION);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
int flag;
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
mInfo.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
mPetrolStation.setName(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
class TabPagerAdapter extends FragmentPagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
// Return fragment with respect to position.
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch (position) {
case SELF_SERVICE_POSITION: {
fragment = SelfServiceFragment.newInstance();
return fragment;
}
case FULL_SERVICE_POSITION: {
fragment = FullServiceFragment.newInstance();
return fragment;
}
}
return null;
}
#Override
public int getCount() {
return intItems;
}
// This method returns the title of the tab according to its position.
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case SELF_SERVICE_POSITION: {
String mSelfService = getResources().getString(R.string.self_service);
return mSelfService;
}
case FULL_SERVICE_POSITION: {
String mFullService = getResources().getString(R.string.full_service);
return mFullService;
}
}
return null;
}
}
}
Any hints about how to solve this issue?
Am I missing some kind of check?
Use a List of boolean type to hold the state of the checkbox. By default fill your collection with a false value.
When you select a checkbox change the state of the map using the set method
As you know When you scroll there will be a call to your adapter there you read the value from the map using get and set it to checkbox
List < Boolean > checkstate = new ArrayList < Boolean > ();
// Inside the adapter constructor
for (i = 0; i < itemSize; i++) {
checkstate.add(false);
}
Inside your Viewholder add below Line what it does is whatever the updated value of checkbox will set to your checkbox. Initially all the Items will be false
yourCheckbox.setChecked(checkstate.get(position));
Now inside onCheckedChanged Listener
if (boxchecked) {
checkstate.set(position, true);
} else {
checkstate.set(position, false);
}
Is it possible to user View pager without fragments. I google it, and all examples use fragments for view pager. I want to pager load only one item from my list, so I want to ask is it possible. Here is my code for main activity, and I want to use UpdateDisplay for viewpager. Any suggestions.
public class MainActivity extends Activity implements OnClickListener{
private Button prev, next;
private TextView tv;
private int number = 0;
private ArrayList<Integer> numbers;
private ViewPager pager;
private MyPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prev = (Button) findViewById(R.id.prevButton);
prev.setOnClickListener(this);
next = (Button) findViewById(R.id.nextButton);
next.setOnClickListener(this);
numbers = new ArrayList<Integer>();
for (int i=0;i<5;i++){
numbers.add(i);
Log.i("Sljedece elemente dodaje u listu", String.valueOf(i));
}
tv = (TextView) findViewById(R.id.rezultatTextView);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
updateDIsplay(number);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.prevButton:
number--;
if (number==-1){
number = 4;
}
updateDIsplay(number);
break;
case R.id.nextButton:
number++;
if (number==5){
number = 0;
}
updateDIsplay(number);
break;
}
}
private void updateDIsplay(int z){
tv.setText(String.valueOf(numbers.get(z)));
}
private class MyPagerAdapter extends PagerAdapter{
#Override
public int getCount() {
return numbers.size();
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return false;
}
}
}
yes it possible. Use a PageAdapter. When instantiateItem is called, you can inflate/instantiate your view, and this to the container. E.g:
private class MyPagerAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView view = new TextView(PagerActivity.this);
view.setText("Item "+position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50, position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
}