Related
I have a Fragment class and an Activity class which is related to that fragment, ViewPager has been initialized inside the Activity of MizActivity
My question is it possible to move ViewPager initialization from Activity class to the Fragment class So that I have better control?
Thanks in advance
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
TextClicked mCallback;
public interface TextClicked{
void sendText(int position);
}
private Activity mContext;
private TvShowEpisode mEpisode;
private ImageView mBackdrop, mEpisodePhoto;
private TextView mTitle, mDescription, mFileSource, mAirDate, mRating, mDirector, mWriter, mGuestStars, mSeasonEpisodeNumber;
private View mDetailsArea;
private Picasso mPicasso;
private Typeface mMediumItalic, mMedium, mCondensedRegular;
private DbAdapterTvShowEpisodes mDatabaseHelper;
private long mVideoPlaybackStarted, mVideoPlaybackEnded;
private boolean mShowFileLocation;
private Bus mBus;
private int mToolbarColor = 0;
private FloatingActionButton mFab;
private PaletteLoader mPaletteLoader;
private ObservableScrollView mScrollView;
private RecyclerView mEpisodesList;
private String mShowId;
private ArrayList<TvShowEpisode> mEpisodes = new ArrayList<TvShowEpisode>();
private static final String SHOW_ID = "showId";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ViewPager mViewPager;
public PlanetAdapter.OnItemClickListener listener;
/**
* Empty constructor as per the Fragment documentation
*/
public TvShowEpisodeDetailsFragment() {}
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode) {
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("showId", showId);
bundle.putInt("season", season);
bundle.putInt("episode", episode);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
mContext = getActivity();
mBus = MizuuApplication.getBus();
mShowFileLocation = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SHOW_FILE_LOCATION, true);
mPicasso = MizuuApplication.getPicassoDetailsView(getActivity());
mMediumItalic = TypefaceUtils.getRobotoMediumItalic(mContext);
mMedium = TypefaceUtils.getRobotoMedium(mContext);
mCondensedRegular = TypefaceUtils.getRobotoCondensedRegular(mContext);
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
// initializing mEpisodes
mShowId = getActivity().getIntent().getExtras().getString(SHOW_ID);
Cursor cursor = mDatabaseHelper.getEpisodes(mShowId);
try {
while (cursor.moveToNext()) {
mEpisodes.add(new TvShowEpisode(mContext, mShowId,
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
));
}
} catch (Exception e) {
} finally {
cursor.close();
} // mEpisodes initialized
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver,
new IntentFilter(LocalBroadcastUtils.UPDATE_TV_SHOW_EPISODE_DETAILS_OVERVIEW));
loadEpisode();
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
loadEpisode();
loadData();
}
};
private void loadEpisode() {
if (!getArguments().getString("showId").isEmpty() && getArguments().getInt("season") >= 0 && getArguments().getInt("episode") >= 0) {
Cursor cursor = mDatabaseHelper.getEpisode(getArguments().getString("showId"), getArguments().getInt("season"), getArguments().getInt("episode"));
if (cursor.moveToFirst()) {
mEpisode = new TvShowEpisode(getActivity(),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
);
mEpisode.setFilepaths(MizuuApplication.getTvShowEpisodeMappingsDbAdapter().getFilepathsForEpisode(
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE))
));
}
cursor.close();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.episode_details, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (TextClicked) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement TextClicked");
}
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBackdrop = (ImageView) view.findViewById(R.id.imageBackground);
mEpisodePhoto = (ImageView) view.findViewById(R.id.episodePhoto);
mDetailsArea = view.findViewById(R.id.details_area);
mTitle = (TextView) view.findViewById(R.id.movieTitle);
mSeasonEpisodeNumber = (TextView) view.findViewById(R.id.textView7);
mDescription = (TextView) view.findViewById(R.id.textView2);
mFileSource = (TextView) view.findViewById(R.id.textView3);
mAirDate = (TextView) view.findViewById(R.id.textReleaseDate);
mRating = (TextView) view.findViewById(R.id.textView12);
mDirector = (TextView) view.findViewById(R.id.director);
mWriter = (TextView) view.findViewById(R.id.writer);
mGuestStars = (TextView) view.findViewById(R.id.guest_stars);
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
// setting RecyclerView
mEpisodesList = (RecyclerView) view.findViewById(R.id.episodesLIST);
// getting episodeslist
ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(mContext.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
mEpisodesList.setAdapter(new PlanetAdapter(episodeslist, new PlanetAdapter.OnItemClickListener() {
#Override public void onItemClick(String item) {
SharedPreferences getPref = getActivity ().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition",0);
mCallback.sendText(pos);
}
}));
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
if (MizLib.isTablet(mContext))
mFab.setType(FloatingActionButton.TYPE_NORMAL);
final int height = MizLib.getActionBarAndStatusBarHeight(getActivity());
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mScrollView.setOnScrollChangedListener(new OnScrollChangedListener() {
#Override
public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
final int headerHeight = mEpisodePhoto.getHeight() - height;
final float ratio = (float) Math.min(Math.max(t, 0), headerHeight) / headerHeight;
final int newAlpha = (int) (ratio * 255);
mBus.post(new BusToolbarColorObject(mToolbarColor, newAlpha));
if (MizLib.isPortrait(mContext)) {
// Such parallax, much wow
mEpisodePhoto.setPadding(0, (int) (t / 1.5), 0, 0);
}
}
});
mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewUtils.setLayoutParamsForDetailsEmptyView(mContext, view,
mBackdrop, mScrollView, this);
}
});
loadData();
mPicasso.load(mEpisode.getEpisodePhoto()).placeholder(R.drawable.bg).config(MizuuApplication.getBitmapConfig()).into(mEpisodePhoto, new Callback() {
#Override
public void onError() {
if (!isAdded())
return;
int width = getActivity().getResources().getDimensionPixelSize(R.dimen.episode_details_background_overlay_width);
int height = getActivity().getResources().getDimensionPixelSize(R.dimen.episode_details_background_overlay_height);
mPicasso.load(mEpisode.getTvShowBackdrop()).placeholder(R.drawable.bg).error(R.drawable.nobackdrop).resize(width, height).config(MizuuApplication.getBitmapConfig()).into(mEpisodePhoto);
}
#Override
public void onSuccess() {
if (mPaletteLoader == null) {
mPaletteLoader = new PaletteLoader(mPicasso, Uri.fromFile(mEpisode.getEpisodePhoto()), new PaletteLoader.OnPaletteLoadedCallback() {
#Override
public void onPaletteLoaded(int swatchColor) {
mToolbarColor = swatchColor;
}
});
mPaletteLoader.addView(mDetailsArea);
mPaletteLoader.setFab(mFab);
mPaletteLoader.execute();
} else {
// Clear old views after configuration change
mPaletteLoader.clearViews();
// Add views after configuration change
mPaletteLoader.addView(mDetailsArea);
mPaletteLoader.setFab(mFab);
// Re-color the views
mPaletteLoader.colorViews();
}
}
});
if (!MizLib.isPortrait(getActivity()))
mPicasso.load(mEpisode.getEpisodePhoto()).placeholder(R.drawable.bg).error(R.drawable.bg).transform(new BlurTransformation(getActivity().getApplicationContext(), mEpisode.getEpisodePhoto().getAbsolutePath() + "-blur", 4)).into(mBackdrop, new Callback() {
#Override public void onError() {
if (!isAdded())
return;
mPicasso.load(mEpisode.getTvShowBackdrop()).placeholder(R.drawable.bg).error(R.drawable.nobackdrop).transform(new BlurTransformation(getActivity().getApplicationContext(), mEpisode.getTvShowBackdrop().getAbsolutePath() + "-blur", 4)).into(mBackdrop, new Callback() {
#Override
public void onError() {}
#Override
public void onSuccess() {
if (!isAdded())
return;
mBackdrop.setColorFilter(Color.parseColor("#aa181818"), android.graphics.PorterDuff.Mode.SRC_OVER);
}
});
}
#Override
public void onSuccess() {
if (!isAdded())
return;
mBackdrop.setColorFilter(Color.parseColor("#aa181818"), android.graphics.PorterDuff.Mode.SRC_OVER);
}
});
}
#Override
public void onDetach() {
mCallback = null; // => avoid leaking, thanks #Deepscorn
super.onDetach();
}
private void loadData() {
// Set the episode title
mTitle.setVisibility(View.VISIBLE);
mTitle.setText(mEpisode.getTitle());
mTitle.setTypeface(mCondensedRegular);
mDescription.setTypeface(mCondensedRegular);
mFileSource.setTypeface(mCondensedRegular);
mDirector.setTypeface(mCondensedRegular);
mWriter.setTypeface(mCondensedRegular);
mGuestStars.setTypeface(mCondensedRegular);
mAirDate.setTypeface(mMedium);
mRating.setTypeface(mMedium);
mSeasonEpisodeNumber.setTypeface(mMediumItalic);
mSeasonEpisodeNumber.setText(getString(R.string.showSeason) + " " + mEpisode.getSeason() + ", " + getString(R.string.showEpisode) + " " + mEpisode.getEpisode());
// Set the movie plot
if (!MizLib.isPortrait(getActivity())) {
mDescription.setBackgroundResource(R.drawable.selectable_background);
mDescription.setMaxLines(getActivity().getResources().getInteger(R.integer.episode_details_max_lines));
mDescription.setTag(true); // true = collapsed
mDescription.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((Boolean) mDescription.getTag())) {
mDescription.setMaxLines(1000);
mDescription.setTag(false);
} else {
mDescription.setMaxLines(getActivity().getResources().getInteger(R.integer.episode_details_max_lines));
mDescription.setTag(true);
}
}
});
mDescription.setEllipsize(TextUtils.TruncateAt.END);
mDescription.setFocusable(true);
} else {
if (MizLib.isTablet(getActivity()))
mDescription.setLineSpacing(0, 1.15f);
}
mDescription.setText(mEpisode.getDescription());
if (mShowFileLocation) {
mFileSource.setText(mEpisode.getAllFilepaths());
} else {
mFileSource.setVisibility(View.GONE);
}
// Set the episode air date
mAirDate.setText(MizLib.getPrettyDatePrecise(getActivity(), mEpisode.getReleasedate()));
// Set the movie rating
if (!mEpisode.getRating().equals("0.0")) {
try {
int rating = (int) (Double.parseDouble(mEpisode.getRating()) * 10);
mRating.setText(Html.fromHtml(rating + "<small> %</small>"));
} catch (NumberFormatException e) {
mRating.setText(mEpisode.getRating());
}
} else {
mRating.setText(R.string.stringNA);
}
if (TextUtils.isEmpty(mEpisode.getDirector()) || mEpisode.getDirector().equals(getString(R.string.stringNA))) {
mDirector.setVisibility(View.GONE);
} else {
mDirector.setText(mEpisode.getDirector());
}
if (TextUtils.isEmpty(mEpisode.getWriter()) || mEpisode.getWriter().equals(getString(R.string.stringNA))) {
mWriter.setVisibility(View.GONE);
} else {
mWriter.setText(mEpisode.getWriter());
}
if (TextUtils.isEmpty(mEpisode.getGuestStars()) || mEpisode.getGuestStars().equals(getString(R.string.stringNA))) {
mGuestStars.setVisibility(View.GONE);
} else {
mGuestStars.setText(mEpisode.getGuestStars());
}
}
Rest of the code
}
Activity
public class TvShowEpisodeDetails extends MizActivity implements TvShowEpisodeDetailsFragment.TextClicked{
private static final String SHOW_ID = "showId";
private ArrayList<TvShowEpisode> mEpisodes = new ArrayList<TvShowEpisode>();
private int mSeason, mEpisode;
private String mShowId, mShowTitle;
private ViewPager mViewPager;
private DbAdapterTvShowEpisodes mDatabaseHelper;
private Bus mBus;
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
ViewUtils.setupWindowFlagsForStatusbarOverlay(getWindow(), true);
ViewUtils.setProperToolbarSize(this, mToolbar);
mShowId = getIntent().getExtras().getString(SHOW_ID);
mSeason = getIntent().getExtras().getInt("season");
mEpisode = getIntent().getExtras().getInt("episode");
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
Cursor cursor = mDatabaseHelper.getEpisodes(mShowId);
try {
while (cursor.moveToNext()) {
mEpisodes.add(new TvShowEpisode(this, mShowId,
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
));
}
} catch (Exception e) {
} finally {
cursor.close();
}
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
mShowTitle = MizuuApplication.getTvDbAdapter().getShowTitle(mShowId);
setTitle(mShowTitle);
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
//notify your recycler views adaper
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
SharedPreferences setPref = this.getSharedPreferences("TvShowEpisodeDetails", Context.MODE_PRIVATE);
setPref.edit().putInt("i", i).apply();
break;
}
}
}
}
#Subscribe
public void onScrollChanged(TvShowEpisodeDetailsFragment.BusToolbarColorObject object) {
ViewUtils.updateToolbarBackground(this, mToolbar, object.getAlpha(),
mEpisodes.get(mViewPager.getCurrentItem()).getTitle(), object.getToolbarColor());
}
public void onResume() {
super.onResume();
mBus.register(this);
ViewUtils.updateToolbarBackground(this, mToolbar, 0, mShowTitle, Color.TRANSPARENT);
}
#Override
public void onPause() {
super.onPause();
mBus.unregister(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onStart() {
super.onStart();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", mViewPager.getCurrentItem());
}
#Override
public void sendText(int position) {
mViewPager.setCurrentItem(position,false);
//Toast.makeText(getContext(), "Item Clicked " + text, Toast.LENGTH_SHORT).show();
}
private class TvShowEpisodeDetailsAdapter extends FragmentPagerAdapter {
public TvShowEpisodeDetailsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return TvShowEpisodeDetailsFragment.newInstance(mShowId, Integer.parseInt(mEpisodes.get(index).getSeason()), Integer.parseInt(mEpisodes.get(index).getEpisode()));
}
#Override
public int getCount() {
return mEpisodes.size();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
setResult(Activity.RESULT_OK);
finish();
}
}
}
}
Yes, a Viewpager can be setup in a Fragment.
You just need to get the right FragmentManager when constructing it i.e use getChildFragmentManager() in mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
From https://developer.android.com/guide/fragments/fragmentmanager
Access the FragmentManager
Accessing in an activity
Every FragmentActivity and subclasses thereof, such as
AppCompatActivity, have access to the FragmentManager through the
getSupportFragmentManager() method.
Accessing in a Fragment
Fragments are also capable of hosting one or more child fragments.
Inside a fragment, you can get a reference to the FragmentManager that
manages the fragment's children through getChildFragmentManager().
I have a navigation activity, where i also have a recycle view and a toolbar, to use the toolbar and the recycle view on this view, I created a separate XML layout like this:
<android.support.design.widget.CoordinatorLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.afcosta.inesctec.pt.android.PlantFeed">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/emerald"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.v7.widget.RecyclerView
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/recycleView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:backgroundTint="#f1c40f"
android:src="#android:drawable/ic_menu_camera" />
<include layout="#layout/content_plant_feed" />
</android.support.design.widget.CoordinatorLayout>
After this I included this layout on my main activity like this:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_plant_feed"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_plant_feed"
app:menu="#menu/activity_plant_feed_drawer"
android:background="#color/white"/>
</android.support.v4.widget.DrawerLayout>
I am populating the recycler view with data of my database using also cardview, the thing is that with this approach (using include) my recycle view doesn't scroll, i have a lot of items but it always show just 4 of them.
my adapter:
public class PlantFeedAdapter extends RecyclerView.Adapter<PlantFeedAdapter.ViewHolder> {
private OnItemClickListener listener;
public interface OnItemClickListener {
void onRowClick(int position, String name, int id, View view);
void onTitleClicked(int position, int id, View clickedview);
void onImageClicked(int position,int id, View clickedview);
void onReportClicked(int position, int id,String name, View clickedview);
void onUserIconClicked(int position, int id, View clickedview);
void onUsernameClicked(int position, int id, View clickedview);
void onAvaliationClicked(int position, int id,String name, View clickedview);
}
private ArrayList<PlantPhotoUser> photos;
private Context context;
public PlantFeedAdapter(Context context, ArrayList<PlantPhotoUser> photos, OnItemClickListener listener) {
this.photos = photos;
this.context = context;
this.listener = listener;
}
#Override
public PlantFeedAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.plant_feed_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final PlantFeedAdapter.ViewHolder viewHolder, final int i) {
viewHolder.name.setText(photos.get(i).getSpecie());
viewHolder.username.setText(photos.get(i).getUsernName());
viewHolder.data.setText(photos.get(i).getDate().split("T")[0]);
Log.d("data123",(photos.get(i).getDate().toString()));
final String urlFoto = "http://10.0.2.2:3000/" + photos.get(i).getPath();
viewHolder.userIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onUserIconClicked(viewHolder.getAdapterPosition(), photos.get(i).getUserId(), view);
}
}
});
viewHolder.username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onUsernameClicked(viewHolder.getAdapterPosition(),photos.get(i).getUserId(), view);
}
}
});
viewHolder.plantImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onImageClicked(viewHolder.getAdapterPosition(), photos.get(i).getIdPlant(), view);
}
}
});
viewHolder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onTitleClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),v);
}
}
});
viewHolder.reportImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onReportClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),photos.get(i).getSpecie(),v);
}
}
});
viewHolder.avaliationFoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onAvaliationClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),photos.get(i).getSpecie(),v);
}
}
});
Picasso.with(context)
.load(urlFoto)
.resize(300, 300)
.into(viewHolder.plantImg);
}
#Override
public int getItemCount() {
return photos.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView name;
private ImageView userIcon;
private TextView avaliationFoto;
private ImageView plantImg;
private ImageView foto;
private TextView username;
private ImageView reportImage;
private TextView data;
public ViewHolder(View view) {
super(view);
data = (TextView)view.findViewById(R.id.data);
name = (TextView) view.findViewById(R.id.plantName);
avaliationFoto = (TextView)view.findViewById(R.id.Avaliation);
userIcon = (ImageView)view.findViewById(R.id.userIcon);
plantImg = (ImageView)view.findViewById(R.id.plantPhoto);;
username = (TextView)view.findViewById(R.id.username);
reportImage = (ImageView)view.findViewById(R.id.cameraForbiden);
}
}
}
activity code:
public class PlantFeed extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,PlantFeedAdapter.OnItemClickListener {
//initialize fields
String token;
ArrayList<PlantPhotoUser> photos = new ArrayList<>();
VolleyService mVolleyService;
IResult mResultCallback = null;
final String GETREQUEST = "GETCALL";
final String URL = "http://10.0.2.2:3000/fotos";
String date;
String lat;
String lon;
String alt;
PlantFeedAdapter plantFeedAdapter;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plant_feed);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(PlantFeed.this,CameraCapture.class);
startActivity(i);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
recyclerView = (RecyclerView)findViewById(R.id.recycleView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager((new LinearLayoutManager(this)));
plantFeedAdapter = new PlantFeedAdapter(getApplicationContext(), photos,PlantFeed.this);
recyclerView.setAdapter(plantFeedAdapter);
token = checkForToken();
initVolleyCallback();
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.getDataVolley(GETREQUEST,URL,token);
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d("HELLL","hi1");
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
PlantPhotoUser plantPhotoUser;
Log.d("HELLLL","hi");
for (int i=0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Log.d("objeto",object.toString());
int userId = object.getInt("userId");
Log.d("objeto",String.valueOf(userId));
String username = object.getJSONObject("user").getString("username");
Log.d("objeto",String.valueOf(username));
int plantId = object.getInt("plantId");
Log.d("objeto",String.valueOf(plantId));
String specie = object.getJSONObject("plant").getString("specie");
Log.d("objeto",String.valueOf(specie));
String path = object.getString("image");
Log.d("objeto",String.valueOf(path));
int fotoId = object.getInt("id");
if(object.getString("date") != null){
date = object.getString("date");
}
if(object.getString("lat") != null){
lat = object.getString("lat");
}
if(object.getString("lon") != null){
lon = object.getString("lon");
}
if(object.getString("altitude") != null){
alt = object.getString("altitude");
}
plantPhotoUser = new PlantPhotoUser(fotoId,plantId,userId,path,specie,date,lat,lon,alt,username);
photos.add(plantPhotoUser);
} catch (JSONException e) {
e.printStackTrace();
}
}
plantFeedAdapter.notifyDataSetChanged();
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d("FAIL",error.toString());
}
};
}
public String checkForToken() {
SharedPreferences sharedPref = getSharedPreferences("user", MODE_PRIVATE);
String tokenKey = getResources().getString(R.string.token);
String token = sharedPref.getString(getString(R.string.token), tokenKey); // take the token
return token;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Intent i = new Intent(PlantFeed.this,UserProfile.class);
startActivity(i);
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.plant_feed, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
Intent i = new Intent(PlantFeed.this,CameraCapture.class);
startActivity(i);
} else if (id == R.id.nav_gallery) {
Intent i = new Intent(PlantFeed.this,PlantFeed.class);
startActivity(i);
} else if (id == R.id.nav_slideshow) {
Intent i = new Intent(PlantFeed.this,FamilyLibrary.class);
startActivity(i);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onRowClick(int position, String name, int id, View view) {
}
#Override
public void onTitleClicked(int position, int id, View clickedview) {
Intent i = new Intent(this,PhotosForPlant.class);
i.putExtra("plantId",String.valueOf(id));
startActivity(i);
}
#Override
public void onImageClicked(int position, int id, View clickedview) {
Intent i = new Intent(this,PhotosForPlant.class);
i.putExtra("plantId",String.valueOf(id));
startActivity(i);
}
#Override
public void onReportClicked(int position, int id, String name, View clickedview) {
Log.d("HELLLO","HELLOO");
showDialogReport(id,name);
}
#Override
public void onUserIconClicked(int position, int id, View clickedview) {
Intent i = new Intent(this,UserProfile.class);
i.putExtra("userId",id);
startActivity(i);
}
#Override
public void onUsernameClicked(int position, int id, View clickedview) {
Intent i = new Intent(this,UserProfile.class);
i.putExtra("userId",id);
startActivity(i);
}
#Override
public void onAvaliationClicked(int position, int id, String name, View clickedview) {
}
Any tip?
hello there i have created an app for playing Youtube videos i works fine but i want when i click on next button the next videos plays. how i will create an array for it which contain the youtube videos link. i m new to Android programming plz help.
public class TutorialsActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String DEVELOPER_KEY = "AIzaSyAIeerJ_5ClQHLtIpXtk5DH2S4mZ9lwGKs";
private static final String VIDEO_ID = "eQW4R5gLlUk";
private static final String VIDEO_ID1 = "H2c_x4YWx7I";
private static final int RECOVERY_DIALOG_REQUEST = 1;
YouTubePlayerFragment myYouTubePlayerFragment;
Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorials);
myYouTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager().findFragmentById(R.id.youtubeplayerfragment);
myYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
btnNext = (Button) findViewById(R.id.btnNext);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, final YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
player.cueVideo(VIDEO_ID1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView)findViewById(R.id.youtubeplayerfragment);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
}
just i shared my working source of your requirement.
SampleActivity.java
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import java.util.ArrayList;
import www.ns7.tv.R;
import www.ns7.tv.controller.YoutubeManager;
public class SampleActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener, View.OnClickListener {
private static final String TAG = "YoutubeLiveTvActivity";
private Button mBtnNext;
private YouTubePlayerView mYouTubePlayerView = null;
private YouTubePlayer mLiveTvPlayer = null;
private ArrayList<String> mVideoIdList = new ArrayList<>();
private int mOffset = 0;
private String mCurrentVideoId;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.sample);
mBtnNext = (Button) findViewById(R.id.btnNext);
mYouTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_view);
mYouTubePlayerView.initialize(YoutubeManager.YOUTUBE_API_KEY, this);
mBtnNext.setOnClickListener(this);
updateVideoIdList();//add all video id in list
updateVideoId();//set current video id to mCurrentVideoId string
}
private void updateVideoId() {
if (mOffset >= mVideoIdList.size())
mOffset = 0;
mCurrentVideoId = mVideoIdList.get(mOffset);
}
private void updateVideoIdList() {
mVideoIdList.clear();
mVideoIdList.add("p0JcLbXfYXA");
mVideoIdList.add("63pKwVE4Uog");
mVideoIdList.add("QJXsurYoJ10");
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
try {
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
mLiveTvPlayer = youTubePlayer;
// mLiveTvPlayer.setOnFullscreenListener(YoutubeLiveTvActivity.this);
if (!b) {
mYouTubePlayerView.setVisibility(View.VISIBLE);
youTubePlayer.loadVideo(mCurrentVideoId);
}
} catch (Exception e) {
Log.e(TAG, " error : ", e);
}
}
#Override
protected void onResume() {
super.onResume();
if (mLiveTvPlayer == null) {
mYouTubePlayerView.initialize(YoutubeManager.YOUTUBE_API_KEY, this);
} else {
mLiveTvPlayer.loadVideo(mCurrentVideoId);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
#Override
protected void onDestroy() {
if (mLiveTvPlayer != null) {
mLiveTvPlayer.release();
}
if (mYouTubePlayerView != null) {
mYouTubePlayerView.removeAllViews();
}
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.btnNext:
{
mOffset++;// move the mOffset to next video id
updateVideoId();
mLiveTvPlayer.loadVideo(mCurrentVideoId);//load next video
}
break;
}
}
}
sample.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/black"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/btnNext"
android:background="#android:color/black"
>
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
/>
</RelativeLayout>
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Next"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
Above code youtube video play at 0 position when you click next button , next video will be play. if list last item reached then it will again move to 0 position.
Output :
I created a base fragment class that handles setting the toolbar title, registering for when the fragment is attached, setting the menu icons and a few other things. My issue is that I've decided to use the PreferencesFragmentCompat for my settings fragment and I cant extend both my BaseFragment and androids PreferencesFragmentCompat. Using an interface here wouldn't help because my BaseFragment has a lot of functionality, and I don't want to duplicate it into each of my fragment classes. Normally to extend two classes, you just do it in two seperate files but because both already extend off Androids Fragment class, I dont see how this is possible. Is there a better way of doing this?
BaseFragment:
public abstract class BaseFragment extends Fragment {
protected View rootView;
protected AppSettings settings;
protected LayoutInflater inflater;
public static void startFragment(Activity activity, BaseFragment newFragment) {
FragmentManager fragManager = ((AppCompatActivity) activity).getSupportFragmentManager();
BaseFragment currentFragment = (BaseFragment) fragManager.findFragmentById(R.id.fragment_container);
// Start the transactions
FragmentTransaction transaction = fragManager.beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
// If there is already a fragment then we want it on the backstack
if (currentFragment != null) {
transaction.addToBackStack(null);
}
// Show it
transaction.commit();
}
#TargetApi(21)
private void lockMode(boolean start) {
if (android.os.Build.VERSION.SDK_INT >= 16) {
if (start) {
getActivity().startLockTask();
} else {
getActivity().stopLockTask();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get a reference to the app settings
settings = AppSettings.getInstance(getActivity());
// Don't want keyboard to stay open between fragments
hideKeyboard();
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
if (toolbarElevation()) {
actionBar.setElevation(4 * getActivity().getResources().getDisplayMetrics().density);
} else {
actionBar.setElevation(0);
}
}
setHasOptionsMenu(true);
}
#Override
public void onResume() {
super.onResume();
// Set the title up
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setTitle(getTitle());
// Enable the home button in the action bar
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
// Change the home button icon for menu or back
if (showUpNavigation()) {
toolbar.setNavigationIcon(R.drawable.ic_navigation_back_white);
} else {
toolbar.setNavigationIcon(R.drawable.ic_menu_white);
}
if (isAppInLockTaskMode() == true && pinnedMode() == false) {
lockMode(false);
}
setDrawerMenu();
}
public boolean getAuthRequired() {
return true;
}
public boolean isBackAllowed() {
return true;
}
public boolean toolbarElevation() {
return true;
}
public String getTitle() {
return "ISOPED";
}
public boolean pinnedMode() {
return false;
}
public boolean showUpNavigation() {
return false;
}
public void hideKeyboard() {
InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
// check if no view has focus:
View v = getActivity().getCurrentFocus();
if (v == null) {
return;
}
inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
public void setDrawerMenu() {
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.drawer_navigation);
Integer menuID = null;
Integer currentMenuId = null;
if (settings.isType(AppSettings.TYPES.PERSONAL)) {
menuID = R.menu.drawer_personal;
} else if (settings.isType(AppSettings.TYPES.PROFESSIONAL)) {
if (getAuthRequired() == true) {
menuID = R.menu.drawer_professional_locked;
} else {
menuID = R.menu.drawer_professional_unlocked;
}
}
if (menuID != null) {
if (navigationView.getTag() != null) {
currentMenuId = (Integer) navigationView.getTag();
}
if (currentMenuId == null || navigationView.getMenu().size() == 0 || currentMenuId != menuID) {
navigationView.getMenu().clear();
navigationView.inflateMenu(menuID);
navigationView.setTag(Integer.valueOf(menuID));
}
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
if (settings.isType(AppSettings.TYPES.PROFESSIONAL) && pinnedMode() && false == isAppInLockTaskMode()) {
inflater.inflate(R.menu.pin_menu, menu);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
switch (item.getItemId()) {
case android.R.id.home:
if (showUpNavigation()) {
getActivity().onBackPressed();
} else {
drawer.openDrawer(GravityCompat.START);
}
return true;
case R.id.menu_pin:
if (isAppInLockTaskMode()) {
PinDialog dialog = new PinDialog((AppCompatActivity) getActivity(), new NavigationCallback((AppCompatActivity) getActivity()) {
#Override
public void run() {
lockMode(false);
}
});
dialog.show();
} else {
lockMode(true);
}
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean isAppInLockTaskMode() {
ActivityManager activityManager;
activityManager = (ActivityManager)
getActivity().getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// For SDK version 23 and above.
return activityManager.getLockTaskModeState()
!= ActivityManager.LOCK_TASK_MODE_NONE;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// When SDK version >= 21. This API is deprecated in 23.
return activityManager.isInLockTaskMode();
}
return false;
}
}
This is a nice example, where you should apply Joshua Bloch's "Favor composition over inheritance" idiom.
You can delegate all the logic that you have applied to BaseFragment to some class FragmentHelper:
public class FragmentHelper {
private final Fragment fragment;
public FragmentHelper(Fragment fragment) {
this.fragment = fragment;
}
public void create(Bundle bundle) {
// `BaseFragment`'s code goes here
}
public void resume() {
// `BaseFragment`'s code goes here
}
...
}
Now in your BaseFragment:
public class BaseFragment {
private FragmentHelper fragmentHelper;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
fragmentHelper = new FragmentHelper(this);
fragmentHelper.create(savedInstanceState);
}
#Override
public void onResume() {
fragmentHelper.resume();
}
}
And the same this should be applied to the class that is extending PreferenceFragment.
Thus, you'd evade from code duplication.
Reference:
Joshua Bloch - Effective Java 2nd edition, Item 16.
When I access the PreferenceScreen, I notice that my custom switch is off. Then I turn it on and restart the app. I went back to the PreferenceScreen and the switch went back off. This doesn't happen when I use the default SwitchPreference. I am able to customize the SwitchPreference the way I want it to be, so the only problem is the switch value not saving. I have four files related to a customize SwitchPreference and all of the Preferences are placed in an extension of a PreferenceFragment
SettingsFragment.java
public class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Settings"
>
<com.example.CustomSwitchPreference
android:key="vibration"
android:title="vibration"
android:summary=""
android:defaultValue="true" />
</PreferenceScreen>
CustomSwitchPreference.java:
public class CustomSwitchPreference extends SwitchPreference {
public CustomSwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSwitchPreference(Context context) {
super(context);
}
#Override
protected View onCreateView( ViewGroup parent )
{
LayoutInflater li = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
return li.inflate( R.layout.customswitch_preference, parent, false);
}
/*
#Override
protected void onBindView(View view) {
MainActivity mainActivity = (MainActivity)getContext();
RelativeLayout relativeLayout = (RelativeLayout)mainActivity.findViewById(R.id.switch_frame);
Switch s = (Switch)relativeLayout.getChildAt(1);
s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
persistBoolean(isChecked);
}
});
super.onBindView(view);
}
*/
}
customswitch_preference.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/switch_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/switch_title"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:layout_alignParentStart="true"/>
<Switch
android:id="#+id/switch_pref"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
/>
</RelativeLayout>
MainActivity.java:
public class MainActivity extends Activity {
private ActionBar actionBar;
private boolean mInit = false;
private boolean showIcon = true;
private Menu m;
private GridFragment gridFragment;
private SettingsFragment settingsFragment;
public ImageButton startButton;
public TextView gameTimer;
public TextView mineCount;
public boolean isVibrating;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsFragment = new SettingsFragment();
actionBar = getActionBar();
actionBar.setTitle("Settings");
actionBar.setCustomView(R.layout.actionbar);
//actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
//actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
ViewGroup actionBarViews = (ViewGroup)actionBar.getCustomView();
startButton = (ImageButton)(actionBarViews.findViewById(R.id.actionBarLogo));
mineCount = (TextView)actionBarViews.findViewById(R.id.topTextViewLeft);
gameTimer = (TextView)actionBarViews.findViewById(R.id.topTextViewRight);
startButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
startButton.setImageResource(R.drawable.smiley2);
break;
case MotionEvent.ACTION_UP:
restartGame();
break;
}
return false;
}
});
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/digital-7 (mono).ttf");
TextView textView;
int[] resources =
{R.id.textViewLeft,R.id.topTextViewLeft,R.id.textViewRight,R.id.topTextViewRight};
for(int r: resources) {
textView = (TextView) findViewById(r);
textView.setTypeface(myTypeface);
}
if (findViewById(R.id.fragment_container) != null){
if (savedInstanceState != null) {
return;
}
}
}
public void restartGame() {
startButton.setImageResource(R.drawable.smiley);
getFragmentManager().beginTransaction().remove(gridFragment).commit();
setText(999, gameTimer);
startGame();
}
private void startGame(){
gridFragment = new GridFragment();
gridFragment.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(R.id.fragment_container, gridFragment,"gridFragment").commit();
}
public void setText(int value, TextView textView){
value = Math.min(999,value);
value = Math.max(-99,value);
textView.setText(String.format("%03d",value));
}
#Override
protected void onStart() {
if (!mInit) {
mInit = true;
Database db = new Database(this);
db.deleteAllSessions();
db.close();
startGame();
}
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
m = menu;
return true;
}
private void openSettings(){
showIcon = false;
gridFragment.pauseTimer();
onPrepareOptionsMenu(m);
actionBar.setDisplayShowCustomEnabled(false);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.hide(gridFragment);
ft.add(android.R.id.content, settingsFragment).commit();
//ft.replace(android.R.id.content,settingsFragment);
}
private void updateSettings(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Map<String, ?> map = sharedPrefs.getAll();
for (Map.Entry<String, ?> entry : map.entrySet()) {
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
}
isVibrating = (Boolean)map.get("vibration");
}
private void closeSettings(){
showIcon = true;
onPrepareOptionsMenu(m);
actionBar.setDisplayShowCustomEnabled(true);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.show(gridFragment);
ft.remove(settingsFragment).commit();
//ft.replace(android.R.id.content,gridFragment);
gridFragment.resumeTimer();
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
openSettings();
return true;
}
else if(id == R.id.backButton){
updateSettings();
closeSettings();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.action_settings);
item.setVisible(showIcon);
item = menu.findItem(R.id.backButton);
item.setVisible(!showIcon);
return super.onPrepareOptionsMenu(menu);
}
}
You're never actually setting or saving the state of the switch. You need to override onBindView to set the initial state of the view, and attach a checked change listener to the Switch (R.id.switch_pref) to listen for changes and persist them into SharedPreferences (you can call persistBoolean to do that).