Can the RecyclerView scroll with the rest of the fragment layouts? - java

I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
The RecyclerView and ViewPager are both set inside viewpager_with_toolbar_overlay.xml Layout , and both has been settup in The Activity.
TvShowEpisodeDetailsFragment is the fragment class which belongs to activity class TvShowEpisodeDetails , the fragment creates as many episodes as a TV Show season can offer.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get non-fixable highlighting and scrolling issues , that is why I set it inside the activity because it does not give those issues.
I need to make it work somehow inside the activity.
My goal is that RecyclerView and ViewPager has to be in the same layout XML file and they both must either be in the activity or fragment class
Is it possible to make the RecyclerView scroll with rest of the fragment layouts?
or
Is it possible to do it programmatically?
Here is the activity
public class TvShowEpisodeDetails extends MizActivity{
#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);
// setting episodeslist
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// setting RecyclerView
mEpisodesList = (RecyclerView) findViewById(R.id.episodesLIST);
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(this.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
PlanetAdapter.OnItemClickListener indicatorCallback = new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(String item) {
SharedPreferences getPref = getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition", 0);
mViewPager.setCurrentItem(pos,false);
}
};
final PlanetAdapter planetAdapter = new PlanetAdapter(episodeslist,indicatorCallback);
mEpisodesList.setAdapter(planetAdapter);
// Setting ViewPager
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
planetAdapter.setSelectedIndex(position);
planetAdapter.notifyDataSetChanged();
mEpisodesList.smoothScrollToPosition(position);
//mEpisodesList.scrollToPosition(position);
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
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);
break;
}
}
}
}
}
viewpager_with_toolbar_overlay
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/awesomepager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#068006"
android:layout_marginTop="450dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/episodesLIST"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:scrollbars="horizontal" />
</LinearLayout>
<include layout="#layout/toolbar_layout" />
</FrameLayout>
Here is the XML layout of the fragment which is inflated in onCreateView of the fragment class
episode_details.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/abc_input_method_navigation_guard">
<com.miz.views.ObservableScrollView
android:id="#+id/observableScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/episodePhoto"
android:layout_width="match_parent"
android:layout_height="#dimen/backdrop_portrait_height"
android:scaleType="centerCrop"
android:src="#drawable/bg" />
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/episodePhoto"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/content_details_fab_negative_margin"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:src="#drawable/ic_play_arrow_white_36dp"
app:fab_colorNormal="#666"
app:fab_type="mini" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fab"
android:layout_marginLeft="#dimen/content_details_baseline_margin"
android:layout_marginTop="#dimen/content_details_title_margin_top"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:layout_toLeftOf="#+id/fab"
android:orientation="vertical">
<TextView
android:id="#+id/movieTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_title" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/content_details_very_small_margin"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_subheader"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/details_area"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#666"
android:baselineAligned="false"
android:elevation="1dp"
android:minHeight="#dimen/content_details_large_margin"
android:orientation="horizontal"
android:paddingLeft="#dimen/content_details_baseline_margin"
android:paddingTop="#dimen/content_details_small_margin"
android:paddingRight="#dimen/content_details_baseline_margin"
android:paddingBottom="#dimen/content_details_small_margin">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsAirDate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textReleaseDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/textView61"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsRating"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/content_details_baseline_margin">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/director"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_movie_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/writer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_edit_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/guest_stars"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_people_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_folder_open_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
</LinearLayout>
</LinearLayout>
</com.miz.views.ObservableScrollView>
<FrameLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:visibility="gone">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</FrameLayout>
Update
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
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();
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 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);
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
...
}
...
}

I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
It's hard to use the RecyclerView outside of the ViewPager page fragment; because you can't synchronize and link the touch/motion events when you scroll the page up/down (or when you swipe to next/previous page) between both the page fragment and a standalone (i.e. activity) RecyclerView. Even that won't be smooth.
So, the RecyclerView should be a part of the ViewPager page.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get unfixable highlighting and scrolling issues
So, now the issue of adding the RecyclerView in the ViewPager fragment is the highlighting issue of the RecyclerView item when you click on any item or when you swipe the ViewPager to right/left page.
But, the main issue is that there is a RecyclerView instance per page, i.e. if you have 5 pages, then you have 5 RecyclerViews.
So, it's a cumbersome to track highlighting only within the RecyclerView adapter class. And hence manipulating that with OnClickListeners solely will have issues of linking these RecyclerView and adapter instances together to update their highlighting item.
So, a simpler approach is to pass a parameter to the RecyclerView adapter with the selected item (which is definitely equals to the current ViewPager page position).
And then do a check in the onBindViewHolder() if the position equals to the passed-in value, then highlight the item; otherwise keep items with the original color.
So, wrapping this up into actions:
Change the adapter constructor to accept a highlighted_position parameter
public PlanetAdapter(ArrayList<PlanetModel> episodeslist,
int highlightedPosition, OnItemClickListener listener)
Whenever you create the ViewPager fragment using newInstance() pass-in the current position of the page fragment:
So, in the TvShowEpisodeDetails activity:
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId,
Integer.parseInt(mEpisodes.get(i).getSeason()),
Integer.parseInt(mEpisodes.get(i).getEpisode()),
i)); // The position
And in the TvShowEpisodeDetailsFragment fragment, register this into a field in the fragment argument:
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode, int position) { // adding position
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
// trimmed code.
bundle.putInt("position", position); // <<<< into the bundle
pageFragment.setArguments(bundle);
return pageFragment;
}
And set that in the adapter creation:
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos);
}
});
And reflect that in the adapter to highlight the item:
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition; // <<< set the position
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) { //<<<<< Highlight the item
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
Log.d("LOG_TAG", "onClick: Highlight item: " + highlightedPos);
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
Log.d("LOG_TAG", "onClick: No highlight: " + highlightedPos);
}
}
}

Related

How to remove empty space when visibility is set to GONE

I've set the visibility of RecyclerView to gone. How would I be able to remove the empty space it takes?
I tried putting layout_height as wrap_content, but it still doesn't show anything.
Recycler View:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_gravity="top"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Card View:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:id="#+id/cardView"
android:backgroundTint="#5A10E7"
android:elevation="90dp"
android:orientation="vertical"
android:textColor="#FFFFFF"
app:cardCornerRadius="25dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.282">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/Requestfulfilled"
android:layout_width="139dp"
android:layout_height="41dp"
android:layout_weight="1"
android:backgroundTint="#4CAF50"
android:clickable="true"
android:defaultFocusHighlightEnabled="true"
android:hint="Request Fullfilled"
android:text="Fulfilled"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/DeleteRequest"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="#+id/RlocationView"
app:layout_constraintTop_toBottomOf="#+id/RlocationView" />
<Button
android:id="#+id/DeleteRequest"
android:layout_width="139dp"
android:layout_height="41dp"
android:backgroundTint="#F44336"
android:clickable="true"
android:defaultFocusHighlightEnabled="true"
android:hint="Delete"
android:text="Delete"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/RlocationView"
app:layout_constraintHorizontal_bias="0.894"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.904" />
<TextView
android:id="#+id/RemailView"
android:layout_width="340dp"
android:layout_height="35dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Email"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/RdateView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/RbloodView"
android:layout_width="116dp"
android:layout_height="35dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Blood Group"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/RlocationView"
app:layout_constraintEnd_toStartOf="#+id/RdateView"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/RemailView" />
<TextView
android:id="#+id/RdateView"
android:layout_width="164dp"
android:layout_height="42dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Date of Requirement"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/RlocationView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/RbloodView"
app:layout_constraintTop_toBottomOf="#+id/RemailView" />
<TextView
android:id="#+id/RlocationView"
android:layout_width="340dp"
android:layout_height="35dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Location"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/Requestfulfilled"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/RdateView" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Code to set Card visibility as GONE:
public class yourRequestActivity extends AppCompatActivity {
private RecyclerView cardView;
private DatabaseReference dbRefForReq, dbRefForResp;
private FirebaseAuth mAuth;
private String AuthUserEmail, UserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.request_response_view);
mAuth = FirebaseAuth.getInstance();
AuthUserEmail = mAuth.getCurrentUser().getEmail();
UserID = mAuth.getCurrentUser().getUid();
dbRefForResp = FirebaseDatabase.getInstance().getReference().child("Responses").child(String.valueOf(UserID));
dbRefForReq = FirebaseDatabase.getInstance().getReference().child("Blood Requests");
dbRefForReq.keepSynced(true);
cardView = (RecyclerView) findViewById(R.id.recycleView);
cardView.setHasFixedSize(true);
cardView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<getDbContents> options =
new FirebaseRecyclerOptions.Builder<getDbContents>()
.setQuery(dbRefForReq, getDbContents.class)
.build();
FirebaseRecyclerAdapter<getDbContents, contentHolder> adapter = new FirebaseRecyclerAdapter<getDbContents, contentHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final contentHolder holder, final int position, #NonNull final getDbContents model) {
final int finalPosition = position + 1;
if (model.getUser().equals(AuthUserEmail)) {
dbRefForReq.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DataSnapshot checkFulfillment = dataSnapshot.child(String.valueOf(("Request " + finalPosition))).child("Fulfillment");
if (checkFulfillment.exists()) {
if (checkFulfillment.child("Fulfilled").getValue().equals("yes")) {
/*------------- Set current user card as visible -----------------*/
holder.frameView.setVisibility(View.VISIBLE);
holder.fulfilled.setVisibility(View.GONE);
holder.requestFulfilled.setVisibility(View.VISIBLE);
holder.userEmail.setText(AuthUserEmail);
holder.bloodGroup.setText(model.getBloodGroup());
holder.dateOfRequirement.setText(model.getDate());
holder.Location.setText(model.getLocation());
////////////////////////////////////////////////////////////////////
}
} else {
holder.frameView.setVisibility(View.VISIBLE);
holder.fulfilled.setVisibility(View.VISIBLE);
holder.requestFulfilled.setVisibility(View.GONE);
/*------------- Set current user card as visible -----------------*/
holder.userEmail.setText(AuthUserEmail);
holder.bloodGroup.setText(model.getBloodGroup());
holder.dateOfRequirement.setText(model.getDate());
holder.Location.setText(model.getLocation());
////////////////////////////////////////////////////////////////////
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else if (model.getUser().equals(null)) {
holder.userEmail.setText("You have not posted any request");
} else {
holder.frameView.setVisibility(View.GONE);
}
/* Fulfilled and Delete button Functionality */
holder.fulfilled.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Map<String, Object> response = new HashMap<>();
response.put("Fulfilled", "yes");
/*-----------------Remove Responses------------------*/
dbRefForResp.removeValue();
///////////////////////////////////////////////////////
/*-----------------Update and insert child with fulfilled status as yes------------------*/
dbRefForReq.child(String.valueOf(("Request " + finalPosition))).child("Fulfillment").setValue(response).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(yourRequestActivity.this, "Request fulfillment status posted", Toast.LENGTH_SHORT).show();
}
});
////////////////////////////////////////////////////////////////////
holder.fulfilled.setVisibility(View.GONE);
holder.requestFulfilled.setVisibility(View.VISIBLE);
}
});
}
#NonNull
#Override
public contentHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.your_request_card, viewGroup, false);
contentHolder contentViewHolder = new contentHolder(view);
return contentViewHolder;
}
};
cardView.setAdapter(adapter);
adapter.startListening();
}
public class contentHolder extends RecyclerView.ViewHolder {
TextView userEmail, bloodGroup, dateOfRequirement, Location, requestFulfilled;
Button fulfilled;
FrameLayout frameView;
public contentHolder(#NonNull View itemView) {
super(itemView);
userEmail = itemView.findViewById(R.id.RemailView);
bloodGroup = itemView.findViewById(R.id.RbloodView);
dateOfRequirement = itemView.findViewById(R.id.RdateView);
Location = itemView.findViewById(R.id.RlocationView);
requestFulfilled = (TextView) itemView.findViewById(R.id.fulfilledTextMessage);
frameView = (FrameLayout) itemView.findViewById(R.id.cardFrame);
fulfilled = (Button) itemView.findViewById(R.id.Requestfulfilled);
}
}
}
I want to remove the blank space which occurs while visibility is set to GONE, as shown in the snapshot below.
Image of empty space on removing top card
Image before setting visibility GONE
Simply remove the object from the list if its user is not equal to AuthUserEmail and notify your adapter.
NO NEED TO MAKE VISBILITY GONE OF THE HOLDER VIEW
Your RecyclerView takes space even if visibility is set to gone. It still takes space because there are items that RecyclerView wants to display. Although you can fix this by removing the items RecyclerView wants to show. It would take a lot of memory if you want show that RecyclerView again because you still have to add the items back. What I would recommend is to wrap your RecyclerView with a layout eg. LinearLayout and set that layout's visibility to gone.
Try doing this:
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Place your RecyclerView here -->
<!-- change visibility of container view -->
</LinearLayout>
*Edit: You didn't explain it well. I get what you want now. You simply have to remove the item from your RecyclerView list. The best way to do this is by using DiffUtil. This a great tutorial online showing how you can implement it in Java. https://codinginflow.com/tutorials/android/room-viewmodel-livedata-recyclerview-mvvm/part-1-introduction
Cover your RecyclerView with a FrameLayout and then set your visibility over there.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_gravity="top"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
If this doesnt works then:
Cover your Cardview which is the layout that you designed for your Recyclerview with a FrameLayout. Anyone of them will surely work out for you.

Make the layout below button

In one of my fragment class, it has two buttons (A and B) on top, used to switch to another fragment when clicked using viewPager.
When buttonA is clicked, it should switch to page A and so on.
When I click button A, how can I make the text in A show below the two buttons?
fragment_menu.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">
<Button
android:id="#+id/buttonA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:padding="15dp"
android:text="ButtonA"
android:textSize="12sp" />
<Button
android:id="#+id/buttonB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:layout_marginRight="15dp"
android:layout_toRightOf="#+id/buttonB"
android:backgroundTint="#color/materialGrey600"
android:padding="15dp"
android:text="ButtonB"
android:textSize="12sp" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
MenuFragment
public class MenuFragment extends BaseFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_menu, container, false);
final ViewPager viewPager = (ViewPager) v.findViewById(R.id.pager);
viewPager.setAdapter(new ViewPagerAdapter(getActivity().getFragmentManager()));
Button btnA = (Button) v.findViewById(R.id.buttonA);
Button btnB = (Button) v.findViewById(R.id.buttonB);
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(0, true);
}
});
btnB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(1, true);
}
});
return v;
}
}
ViewPagerAdapter
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new A()
case 1:
return new B()
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
Output
try with below code.hope it is helpful for you ;)
P.S. You just need to set button style as you want :)
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_above="#id/llButton"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/llButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp">
<Button
android:id="#+id/buttonA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:padding="15dp"
android:text="ButtonA"
android:textSize="12sp" />
<Button
android:id="#+id/buttonB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:layout_marginRight="15dp"
android:backgroundTint="#color/colorAccent"
android:padding="15dp"
android:text="ButtonB"
android:textSize="12sp" />
</LinearLayout>
</RelativeLayout>
Since you are using Relative Layout you can add layout_below
<androidx.viewpager.widget.ViewPager
android:layout_below="#id/buttonB"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
you are doing it wrong, You cannot align a button to itself. That's why your buttons are not working properly. In your button B do this:
android:layout_toRightOf="#+id/buttonA"
instead of this:
android:layout_toRightOf="#+id/buttonB"
And to your viewPager add "android:layout_below:"
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/buttonA" />
You have to set your layout like this....
[I think you want something like this 2 button fisrt and then viewpager for change the content ][1]
[1]: https://i.stack.imgur.com/dluXA.png
**Code for main Page **
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:orientation="vertical"
android:padding="5dp"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:padding="10dp"
android:layout_marginTop="10dp"
android:layout_height="match_parent"
android:orientation="horizontal">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/frame_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center_horizontal">
<Button
android:id="#+id/btn_donner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="#drawable/rect_outline"
android:text="Donor's"
android:textAlignment="center"
android:textColor="#color/white" />
<Button
android:id="#+id/btn_blood_bank"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Blood Bank"
android:background="#drawable/rect_outline"
android:layout_weight="2"
android:textAlignment="gravity"
android:textColor="#color/white" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</LinearLayout>
Code For Java File of two Buttons And ViewPager
//Click Event for donor's and blood bank .....
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = null;
if (view == view.findViewById(R.id.btn_donner))
{
fragment = new TabDonnerFragment();
}
else
{
fragment = new TabBloodBankFragment();
}
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frame_content, fragment);
transaction.commit();
}
};
btn_donner.setOnClickListener(listener);
btn_blood_bank.setOnClickListener(listener);
return root;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fragment fragment = null;
fragment = new TabDonnerFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frame_content, fragment);
transaction.commit();
}
}

View search Result in a new Activity

I have a search form on a fragment which works perfectly. At the moment I have a RecyclerView at the bottom of the form but I want it to load the search result on a new activity. Please help
layout.xml:
<LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="55dp"
android:orientation="vertical"
tools:context="com.ranake.rana.Search">
<!-- TODO: Update blank fragment layout -->
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/linearLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:orientation="vertical">
<EditText
android:id="#+id/search_field"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/input_outline2"
android:drawableLeft="#drawable/ic_make"
android:drawablePadding="10dp"
android:gravity="center_vertical"
android:hint="Make"
android:inputType="textPersonName"
android:padding="10dp"
android:textColorHint="#7f8c8d"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="7dp"
android:orientation="vertical">
<EditText
android:id="#+id/className"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/input_outline2"
android:drawableLeft="#drawable/ic_model"
android:drawablePadding="10dp"
android:gravity="center_vertical"
android:hint="Model"
android:inputType="text"
android:padding="10dp"
android:textColorHint="#7f8c8d"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal">
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="42dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="#drawable/button_red_border"
android:text="Clear"
android:textColor="#color/colorPrimary" />
<Button
android:id="#+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="42dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="20dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="#drawable/button_red"
android:text="Search"
android:textColor="#android:color/white" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ProgressBar
android:layout_width="match_parent"
android:id="#+id/progressBar"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/result_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"></android.support.v7.widget.RecyclerView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
Search.java:
public class Search extends Fragment {
private EditText mSearchField;
private Button mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
mUserDatabase = FirebaseDatabase.getInstance().getReference("Cars");
mSearchField = (EditText) view.findViewById(R.id.search_field);
mSearchBtn = (Button) view.findViewById(R.id.search_btn);
mResultList = (RecyclerView) view.findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setNestedScrollingEnabled(false);
mResultList.setLayoutManager(new LinearLayoutManager(getContext()));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
return view;
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(getActivity(), "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("title").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Cars, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Cars, UsersViewHolder>(
Cars.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Cars model, int position) {
viewHolder.setDetails(getActivity().getApplicationContext(), model.getTitle(), model.getDesc(), model.getImage(), model.getMileage(), model.getTrans(), model.getFuel(), model.getPrice(), model.getLocation());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String userTitle, String userDesc, String userImage, String userMileage, String userTrans, String userFuel, String userPrice, String userLocation){
TextView user_title = (TextView) mView.findViewById(R.id.name_text);
TextView user_desc = (TextView) mView.findViewById(R.id.status_text);
ImageView user_image = (ImageView) mView.findViewById(R.id.profile_image);
TextView user_mileage = (TextView) mView.findViewById(R.id.post_mileage);
TextView user_trans = (TextView) mView.findViewById(R.id.post_trans);
TextView user_fuel = (TextView) mView.findViewById(R.id.post_fuel);
TextView user_price = (TextView) mView.findViewById(R.id.post_price);
TextView user_location = (TextView) mView.findViewById(R.id.post_location);
user_title.setText(userTitle);
user_desc.setText(userDesc);
user_mileage.setText(userMileage);
user_trans.setText(userTrans);
user_fuel.setText(userFuel);
user_price.setText(userPrice);
user_location.setText(userLocation);
Glide.with(ctx).load(userImage).into(user_image);
}
}
When the search Button is clicked, I want it to open the new activity and load the results there.
You can pass this searchText to the next Activity (I'm calling it ResultsActivity) by passing it as an extra on the Intent:
private void firebaseUserSearch(String searchText) {
Intent intent = new Intent(getActivity(), ResultsActivity.class);
intent.putExtra("searchText",searchText);
startActivity(intent);
}
Then receive it on the other Activity using Intent.getExtras():
String searchText = getIntent().getExtras().getString("searchText");
And finally populate the RecyclerView from that Activity:
Query firebaseSearchQuery = mUserDatabase.orderByChild("title").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Cars, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Cars, UsersViewHolder>(
Cars.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Cars model, int position) {
viewHolder.setDetails(getActivity().getApplicationContext(), model.getTitle(), model.getDesc(), model.getImage(), model.getMileage(), model.getTrans(), model.getFuel(), model.getPrice(), model.getLocation());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);

fragments not displaying in framelayout

Intro:
To put things into perspective, I am attempting to use fragments to create a Sudoku game.
The Sudoku board consists of 9 sub-grids, each containing 9 cells, so 9 cells in one grid, and 9 of these grids form the Sudoku board, arranged in a 3x3 fashion.
Method:
Home screen containing some information, of which a GridLayout contains 9 Framelayouts where each Sudoku Fragment will be placed into
The 9 Sudoku Fragments will make up the Sudoku board.
sudoku_cell extends a LinearLayout with an onClickListener, since extending a TextView, I was unable to inflate the sudoku_cell layout (Is it possible to do so?)
In my main activity, I have a GridLayout containing 9 FrameLayouts. These layouts have column and row locations set to form a 3x3 matrix, this is where each of the fragments will be added into.
These FrameLayouts are named on a 0-based index: frame00, frame01, frame02, frame10, etc
Documentation says:
As mentioned here on developer.android.com, I am required to have an:
Inflator method for the fragment, i.e. onCreateView() which inflates the fragment
A Layout container of sorts to root/place the fragment in, in the main activity (in my case)
A FragmentManager and FragmentTransactionManager to handle the fragments, adding and commiting them.
Problem:
TL;DR: Simply, my fragments are not showing.
After calling the commit(), I expect to see a 3x3 board of sudoku_grid fragments, each containing 9 sudoku_cells. However, this does not get shown
I have searched SO, reread the documentation, and searched more but cannot understand why it is not showing.
I have tried:
When inflating my fragment, I inflate a sudoku_cell layout instead, this does infact show a 9 cell grid.
However each cell should be a grid containing 9 cells, this leads me to believe that there may be an issue on the Sudoku_Grid - Sudoku_Cell side, possibly the sudoku_cell layout is not being inflated correctly or being rooted correctly.
Usually an LayoutInflator, and ViewGroup is passed allowing one to inflate a layout, but in the case of the sudoku_cell, I cannot find such a method to override, is this the cause?
The code:
sudoku_cell.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/cellText"
android:layout_width="35dp"
android:layout_margin="1px"
android:textSize="18dp"
android:layout_height="35dp"
android:textAlignment="center"
android:textColor="#color/clBlack">
</TextView>
</LinearLayout>
SudokuCell.java
public class SudokuCell extends LinearLayout{
private LinearLayout layout;
private TextView textView;
private Context mContext;
private Point location;
private int index;
public SudokuCell(Context context) {
super(context);
}
public SudokuCell(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = (LinearLayout) inflater.inflate(R.layout.sudoku_cell, this, true);
textView = layout.findViewById(R.id.cellText);
setText("");
}
public void setStaticText(String s){
if (textView != null) {
textView.setText(s);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
}
}
public void setText(String s){
if (textView != null)
textView.setText(s);
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
9 of these sudoku_cell's get added to a sudoku_grid as shown below in the onCreateView() and populateGrid() methods:
sudoku_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2px"
android:id="#+id/grid_layout"
android:columnCount="3"
android:rowCount="3">
</GridLayout>
SudokuGrid.java
public class SudokuGrid extends Fragment{
private GridLayout gridLayout;
private List<GridFragmentListener> listeners = new ArrayList<>();
private Context mActitityContext;
private boolean FRAGMENT_LOCATION_CENTRE;
private float SCREEN_DP;
private int GRID_MARGINS_DP = 1;
private int colorOdd, colorEven;
private List<Integer> presetGrid;
private View previousView;
private Drawable previousViewDrawable;
public void addGridListener(GridFragmentListener gridFragmentListener) {
listeners.add(gridFragmentListener);
}
public void removeGridListener(GridFragmentListener gridFragmentListener) {
listeners.remove(gridFragmentListener);
}
protected void notifyValueChanged(View value) {
for (GridFragmentListener listener : listeners) listener.onValueChange(value);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mActitityContext = getActivity();
View v = inflater.inflate(R.layout.sudoku_grid, container, false);
//set grid view
gridLayout = v.findViewById(R.id.grid_layout);
populateGrid();
return v;
}
private void populateGrid() {
for (int i = 0; i < 9; i++) {
SudokuCell sudokuCell = new SudokuCell(mActitityContext);
sudokuCell.setBackgroundColor(((i % 2) == 0) ? R.color.clOdd : R.color.clEven);
System.out.printf("Sudoku Cell ID [ index = " + String.valueOf(i) + " ] - getId() = " + sudokuCell.getId());
sudokuCell.setLocation(getPoint(i));
sudokuCell.setIndex(i);
sudokuCell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notifyValueChanged(view);
}
});
sudokuCell.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
SudokuCell cell = (SudokuCell) view;
if (b)
view.setBackgroundColor(ContextCompat.getColor(mActitityContext, R.color.clSelected));
else
view.setBackgroundColor(ContextCompat.getColor(mActitityContext, (cell.getIndex() % 2 == 0) ? R.color.clOdd : R.color.clEven));
}
});
sudokuCell.setStaticText(String.valueOf(i));
gridLayout.addView(sudokuCell, i);
}
}
private Point getPoint(int i) {
int y = 0;
while (i > 2){
y++;
i -= 3;
}
return new Point(i, y);
}
#Override
public void onStart() {
super.onStart();
try {
addGridListener((GridFragmentListener) getActivity());
} catch (ClassCastException e) {
throw new ClassCastException(
getActivity().getClass().toString()
+ " does not implement the DetailsFragment.DetailsFragmentListener interface.");
}
}
#Override
public void onStop() {
super.onStop();
removeGridListener((GridFragmentListener) getActivity());
}
}
In my main activity, I handle the creation of 9 sudoku_grid fragments which are placed into each respective FrameLayout, to form a 3x3 matrix of Sudoku_Grids, which will form the Sudoku board
activity_main_sudoku.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="wrap302.nmu.task1.MainActivitySudoku"
android:background="#color/clDarkGrey">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/linearLayout2">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:text="#string/app_title"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:textColor="#color/clWhite"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textAlignment="center"
android:textStyle="bold"
android:fontFamily="sans-serif"/>
<TextView
android:text="#string/lblScore"
android:textColor="#color/clWhite"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/lblScore"
android:textAppearance="#style/TextAppearance.AppCompat.Button" android:textAlignment="center"
android:layout_marginBottom="5dp"/>
</LinearLayout>
<GridLayout
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="3"
android:rowCount="3"
android:id="#+id/main_sudokugrid_container">
<FrameLayout
android:layout_column="0"
android:layout_row="0"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame00"/>
<FrameLayout
android:layout_column="1"
android:layout_row="0"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame01"/>
<FrameLayout
android:layout_column="2"
android:layout_row="0"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame02"/>
<FrameLayout
android:layout_column="0"
android:layout_row="1"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame10"/>
<FrameLayout
android:layout_column="1"
android:layout_row="1"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame11"/>
<FrameLayout
android:layout_column="2"
android:layout_row="1"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame12"/>
<FrameLayout
android:layout_column="0"
android:layout_row="2"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame20"/>
<FrameLayout
android:layout_column="1"
android:layout_row="2"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame21"/>
<FrameLayout
android:layout_column="2"
android:layout_row="2"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame22"/>
</GridLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center" android:id="#+id/linearLayout">
<GridLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingTop="0dp">
<Button
android:layout_row="0"
android:layout_column="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn1"
android:text="1"/>
<Button
android:layout_row="0"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn2"
android:text="2"/>
<Button
android:layout_row="0"
android:layout_column="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn3"
android:text="3"/>
<Button
android:layout_row="1"
android:layout_column="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn4"
android:text="4"/>
<Button
android:layout_row="1"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn5"
android:text="5"/>
<Button
android:layout_row="1"
android:layout_column="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn6"
android:text="6"/>
<Button
android:layout_row="2"
android:layout_column="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn7"
android:text="7"/>
<Button
android:layout_row="2"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn8"
android:text="8"/>
<Button
android:layout_row="2"
android:layout_column="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn9"
android:text="9"/>
<Button
android:layout_row="0"
android:layout_column="3"
android:layout_rowSpan="3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_vertical"
android:id="#+id/btnClear"
android:text="Clear"/>
</GridLayout>
</LinearLayout>
</RelativeLayout>
MainActivitySudoku.java
public class MainActivitySudoku extends AppCompatActivity implements GridFragmentListener {
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_sudoku);
createSudokuGrid();
}
private void createSudokuGrid() {
fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransactionManager = fragmentManager.beginTransaction();
fragmentTransactionManager.add(R.id.frame00, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame01, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame02, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame10, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame11, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame12, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame20, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame21, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame22, new SudokuGrid());
fragmentTransactionManager.commit();
}
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Activity Started & Viewable", Toast.LENGTH_SHORT).show();
}
// GridFragmentListener
#Override
public void onValueChange(View view) {
//todo something here with received view
}
}
Well, the solution proved simpler than expected.
In short, the solution was to move the SudokuCell constructor code from the
SudokuCell(Context context, AttributeSet attrs)
to the
SudokuCell(Context context)
since that was the constructor I was calling.
A few other changes can be made for improvement, this solves the fragments not being displayed.
Quite a simple error
Ok - I have given you a sample of how to add your fragments so they will display. If you go through this and emulate the process this will assist you. I've used basic examples in the layout so we can have ids to use in the classes.
You'll also need to manage the app lifecycle and the back press button on how you want to manage your stack with your fragments and maintaining any data.
Activity
public class MyActivity extends Activity {
Fragment fragment;
FrameLayout frameLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_myactivity);
View view = this.findViewById(android.R.id.content);
frameLayout = (FrameLayout) findViewById(R.id.frag);
fragment = new MyFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frag, fragment);
fragmentTransaction.commit();
}
}
Layout for Activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
.../...>
.../...
<FrameLayout
android:id="#+id/frag"
// sort out your layout here with the frameLayouts
android:layout_below="#+id/your_id"
/>
.../...
</RelativeLayout>
Fragment
public class MyFragmentextends Fragment {
FragmentManager fragmentManager;
Fragment fragment;
public static MyFragmentnewInstance(String item {
fragment =
new MyFragment();
// pass data from activity
Bundle args = new Bundle();
args.putString(ITEM, item);
fragment.setArguments(args);
return fragment;
}
public DeliveryDisplayFromDispenserFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
item = getArguments().getString(ITEM);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =
inflater.inflate(R.layout.myfragment, container, false);
}
}
Layout for Fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
.../...>
// fragment layout
</RelativeLayout>

Android - OnClick inside gridview row

I'm trying to launch a activity from a button inside my gridview item, meaning that when user click on gridview Item it should do one function and when the user click on the button inside the gridview item it should do another function, let me elaborate, here is my single item layout that is being populated inside of my gridview;
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal"
app:cardCornerRadius="5dp"
app:cardElevation="3dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true">
<RelativeLayout
android:id="#+id/single_row"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imgFood"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
app:civ_border_color="#ffffff"
app:civ_border_width="2dp"
app:civ_shadow="true"
app:civ_shadow_color="#000000"
app:civ_shadow_radius="10" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imgFood">
<TextView
android:id="#+id/txtName"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/currentid"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_below="#+id/txtName"
android:text="Current ID : "
android:visibility="visible"
/>
<TextView
android:id="#+id/studentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp"
android:layout_below="#+id/txtName"
android:layout_toRightOf="#+id/currentid"
android:layout_marginEnd="30dp"
android:layout_marginRight="30dp"
/>
</RelativeLayout>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="end"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/editit"
android:background="#android:drawable/btn_dialog"/>
</RelativeLayout>
here is how the above layout looks:
and here is my adapter getview from where I try to do the intent/actions from;
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.txtName = (TextView) row.findViewById(R.id.txtName);
holder.txtPrice = (TextView) row.findViewById(R.id.studentid);
holder.imageView = (CircularImageView) row.findViewById(R.id.imgFood);
holder.dit = (Button) row.findViewById(R.id.editit);
final ViewHolder finalHolder = holder;
holder.dit.setOnClickListener(new View.OnClickListener() {
String getname = finalHolder.txtName.getText().toString();
String gethandicap = finalHolder.txtPrice.getText().toString();
#Override
public void onClick(View v) {
// Do something
Intent editintent = new Intent(context, MainActivity.class);
editintent.putExtra("studentname", getname);
editintent.putExtra("studentid", getID);
context.startActivity(editintent);
}
});
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Sudentdb student = studentsList.get(position);
holder.txtName.setText(student.getName());
holder.txtPrice.setText(student.getID());
if (student.getImage() != null && student.getImage().length > 0) {
Glide.with(context)
.load(student.getImage())
.into(holder.imageView);
} else {
holder.imageView.setImageBitmap(null);
}
return row;
}
The problem I'm having is that the button inside the gridview item is not performing any actions, in log it only says ACTION_DOWN and since I added a button inside the item the item onclick also doesn't work.
EDIT; ADDING GRIDVIEW ONCLICK AND LAYOUT
gridView = (GridView) findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new StudentListAdapter(this, R.layout.food_items, list);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String dataFromGrid;
dataFromGrid = ((TextView)(view.findViewById(R.id.txtName))).getText().toString();
Intent i = new Intent(getApplicationContext(), Student.class);
i.putExtra("unfromstudent",dataFromGrid);
startActivity(i);
gridview layout (I have tried focusable and clickable)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
>
<GridView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:id="#+id/gridView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:columnWidth="120dp"
android:gravity="center"
android:layout_margin="2dp"
android:numColumns="1"
/>
</RelativeLayout>
Change you XML, i have tested below xml its works fine with
GridView
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal"
app:cardCornerRadius="5dp"
app:cardElevation="3dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:orientation="horizontal">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imgFood"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_margin="10dp"
app:civ_border_color="#ffffff"
app:civ_border_width="2dp"
app:civ_shadow="true"
app:civ_shadow_color="#000000"
app:civ_shadow_radius="10" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_weight="1"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/txtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/currentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtName"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:text="Current ID : "
android:visibility="visible" />
<TextView
android:id="#+id/studentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtName"
android:layout_marginEnd="30dp"
android:layout_marginRight="30dp"
android:layout_toRightOf="#+id/currentid"
android:text="ID"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="30dp"
android:layout_height="30dp">
<Button
android:id="#+id/editit"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="end"
android:background="#android:drawable/btn_dialog"
android:focusable="false" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Your Grid View XML will be Like this.
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true">
</GridView>
I don't have enough reputation so i can't comment your question, why don't you use a recyclerview with a gridLayoutManager? You can see a basic example here .
After that you can implement your recyclerview adapter this way:
public class StudentsAdapter extends RecyclerView.Adapter<StudentsAdapter.ViewHolder> {
private final OnStudentItemClickListener mListener;
private Context mContext;
private List<Student> mStudents;
public StudentsAdapter(Context context, List<Student> items, OnStudentItemClickListener listener) {
mContext = context;
mStudents =items;
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_student, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Student student = mStudents.get(position);
holder.mTextName.setText(student.getName());
holder.mTextPrice.setText(student.getID());
if (student.getImage() != null && student.getImage().length > 0) {
Glide.with(context)
.load(student.getImage())
.into(holder.imageView);
} else {
holder.imageView.setImageBitmap(null);
}
}
#Override
public int getItemCount() {
return mStudents.size();
}
public interface OnStudentItemClickListener {
void onStudentItemClick(Student student);
void onStudentButtonClick(Student student);
}
public class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
TextView mTextName;
TextView mTextPrice;
CircleImageView mImageView;
Button mDit;
public ViewHolder(View view) {
super(view);
mTextName = (TextView) view.findViewById(R.id.txtName);
mTextPrice = (TextView) view.findViewById(R.id.studentid);
mImageView = (CircleImageView) view.findViewById(R.id.imgFood);
mDit = (Button) view.findViewById(R.id.editit);
mDit.setOnClickListener(view1 -> {
if (null != mListener) {
mListener.onStudentButtonClick(mStudents.get(getAdapterPosition()));
}
});
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (null != mListener) {
mListener.onStudentItemClick(mStudents.get(getAdapterPosition()));
}
}
}
}

Categories