I am working on a very big project and I am told to write code in a very very efficient way. I have normally written my code but I want the intro layout also to be using mvvm. how can I do that?
my normal welcome activity is below
public class WelcomeActivity extends AppCompatActivity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
//private Button btnSkip, btnNext;
private LoginSession prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
prefManager = new LoginSession(this);
if (!prefManager.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}
// 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.activity_welcome);
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.welcome_slide1,
R.layout.welcome_slide2,
R.layout.welcome_slide3
};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
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() {
prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
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(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);
}
}
}
My sharedpreferences is as below
public class LoginSession {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
public LoginSession(Context context) {
this._context = context;
pref = _context.getSharedPreferences(Constants.PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createLoginSession(JsonObject jsonObject)
{
editor.putBoolean(Constants.LOGGED_IN,true);
editor.putString(Constants.API_TOKEN,jsonObject.get("token_key").getAsString());
editor.putString(Constants.USERNAME,jsonObject.get("username").getAsString());
editor.putInt(Constants.ID,jsonObject.get("id").getAsInt());
editor.commit();
}
public boolean isLoggedIn() {
return pref.getBoolean(Constants.LOGGED_IN, false);
}
public Map<String, String> getLoginDetails() {
Map<String, String> logindetailsMap=new HashMap<>();
logindetailsMap.put(Constants.LOGGED_IN,pref.getString(Constants.LOGGED_IN,null));
logindetailsMap.put(Constants.USERNAME,pref.getString(Constants.USERNAME,null));
logindetailsMap.put(Constants.API_TOKEN,pref.getString(Constants.API_TOKEN,null));
logindetailsMap.put(Constants.ID, String.valueOf(pref.getInt(Constants.ID,0)));
return logindetailsMap;
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
I have already used livedata. please help me modify this code
For starters, you should use data binding instead of "findViewById". This would be a good starting point to see how to bind your fields and buttons.
Also , please see how the code is divided into View, ViewModel and Model
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 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
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);
}
I have activity for fullscreen browsing of images (something like gallery). In this activity I have ViewPager with offscreen limit 6. I use TouchImageView for my images.
The problem is, that when I first zoom image and swipe to another photo, I want to see not zoomed photo when I return to it. TouchImageView has resetZoom() function, but how can I get offscreen page view from the FragmentStatePageAdapter or from ViewPager?
Here's code of my activity:
public class ImageSlidesActivity extends FragmentActivity implements ViewPager.OnPageChangeListener {
final int PAGE_LIMIT = 6;
final int PAGE_MARGIN = 8;
long userID;
long deviceID;
String key;
String[] mAttachments;
ImageSlidesAdapter mAdaper;
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.activity_image_slides);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
//actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#33ffffff")));
Intent intent = getIntent();
mAttachments = intent.getStringArrayExtra("attachments");
int position = intent.getIntExtra("position", 0);
SharedPreferences pref = getApplicationContext().getSharedPreferences("authData", 0);
key = pref.getString("key", null);
userID = pref.getLong("userID", 0);
deviceID = pref.getLong("deviceID", 0);
setPageIndicator(position);
mAdaper = new ImageSlidesAdapter(getSupportFragmentManager(), mAttachments);
final View container = findViewById(R.id.container);
container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActionBar().hide();
container.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
});
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdaper);
mPager.setOnPageChangeListener(this);
mPager.setOffscreenPageLimit(PAGE_LIMIT);
mPager.setCurrentItem(position-1);
/* cause bug with the white strip
final float density = getResources().getDisplayMetrics().density;
mPager.setPageMargin((int) (PAGE_MARGIN * density + 0.5f));
mPager.setPageMarginDrawable(android.R.color.black);
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.image_slides, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
setPageIndicator(position+1);
}
#Override
public void onPageScrollStateChanged(int state) {
}
private void setPageIndicator(int page) {
setTitle(Integer.toString(page) + "/" + Integer.toString(mAttachments.length));
}
/**
* A fragment containing zoomable image.
*/
public static class ShowImageFragment extends Fragment {
String mAlias;
long mUserId;
long mDeviceId;
String mKey;
TouchImageView mImage;
static ShowImageFragment newInstance(String alias, long userId, long deviceId,
String key) {
ShowImageFragment f = new ShowImageFragment();
Bundle args = new Bundle();
args.putString("alias", alias);
args.putLong("userID", userId);
args.putLong("deviceID", deviceId);
args.putString("key", key);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
mAlias = bundle.getString("alias");
mUserId = bundle.getLong("userID");
mDeviceId = bundle.getLong("deviceID");
mKey = bundle.getString("key");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_slides, container, false);
mImage = (TouchImageView) rootView.findViewById(R.id.imageView);
final ProgressBar prBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
new AsyncTask<Void, Void, Bitmap>() {
#Override
protected Bitmap doInBackground(Void... voids) {
try {
String[] links = API.getImageLinkByAlias(mAlias, mUserId,
mDeviceId, mKey);
return ImageLoader.getInstance().loadImageSync(links[1]);
} catch (Exception e) {
// TODO: handle exceptions
e.printStackTrace();
cancel(true);
return null;
}
}
#Override
protected void onPostExecute(Bitmap bitmap) {
prBar.setVisibility(View.GONE);
if (bitmap == null) { return; }
mImage.setImageBitmap(bitmap);
mImage.setVisibility(View.VISIBLE);
mImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (getActivity().getActionBar().isShowing()) {
getActivity().getActionBar().hide();
} else {
getActivity().getActionBar().show();
}
}
});
}
}.execute();
return rootView;
}
}
public class ImageSlidesAdapter extends FragmentStatePagerAdapter {
private String[] mAliases;
public ImageSlidesAdapter(android.support.v4.app.FragmentManager fm, String[] aliases) {
super(fm);
mAliases = aliases;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return ShowImageFragment.newInstance(mAliases[position], userID, deviceID, key);
}
#Override
public int getCount() {
return mAliases.length;
}
}
}
I overrided onPageSelected method and I get views by calling getChildAt().
#Override
public void onPageSelected(int position) {
setPageIndicator(position+1);
if (position > 0) {
View view = mPager.getChildAt(position -1);
if (view != null) {
TouchImageView img = (TouchImageView) view.findViewById(R.id.image);
img.resetZoom();
}
}
if (position < mPager.getChildCount() - 1) {
View view = mPager.getChildAt(position + 1);
if (view != null) {
TouchImageView img = (TouchImageView) view.findViewById(R.id.image);
img.resetZoom();
}
}
}
It can also be achieved by setting a normal page transformer in the view pager
binding.viewPager.setPageTransformer { page, position ->
// Reset zoom on previous/next item
if (position == -1f || position == 1f) {
(page as PhotoView).apply {
scale = 1f
}
}
}