I'm using RecyclerView to display list of elements and from that list u can go to detailed screen, which is view pager fragment. My problem is that first element I navigate to (from RecyclerView) is displayed incorrectly - it has NestedScrollView, which I cannot fully scroll down. If I swype left or right to next pages, they are fine, it's always one that is loaded as first.
My Adapter class is following;
public class ApodViewAdapter extends FragmentStatePagerAdapter {
private ArrayList<APOD> mDataset;
public ApodViewAdapter(FragmentManager fm, ArrayList<APOD> apodsList) {
super(fm);
setData(apodsList);
}
public void setData(ArrayList<APOD> apodsList){
if(apodsList!=null){
this.mDataset= apodsList;
notifyDataSetChanged();
}
}
#Override
public Fragment getItem(int position) {
return new ApodViewFragment().newInstance(mDataset.get(position), position);
}
#Override
public int getCount() {
return mDataset.size();
}
}
Fragment Activity:
public class ApodViewFragment extends Fragment implements DataInterface, AppBarLayout.OnOffsetChangedListener {
private ImageView mApodImageView;
private TextView mTextView;
private Toolbar mToolbar;
private AppBarLayout mAppBarLayout;
private TextView mTitle;
private FrameLayout mContentFl;
private APOD mApodElement;
private static final String KEY_CONTENT = "ApodViewFragment:Content";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mApodElement = (APOD) savedInstanceState.getSerializable(KEY_CONTENT);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(KEY_CONTENT, mApodElement);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_apod_material, container, false);
mApodImageView = (ImageView) rootView.findViewById(R.id.apod_view_apod_iv);
mTextView = (TextView) rootView.findViewById(R.id.apod_view_text_tv);
mTitle = (TextView) rootView.findViewById(R.id.apod_fragment_title_tv);
mContentFl = (FrameLayout) rootView.findViewById(R.id.fragment_apod_fl);
mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
mAppBarLayout = (AppBarLayout) rootView.findViewById(R.id.app_bar_layout);
mAppBarLayout.addOnOffsetChangedListener(this);
ViewTreeObserver vto = mContentFl.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
setHeroImageMaxHeight();
ViewTreeObserver obs = mContentFl.getViewTreeObserver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
obs.removeOnGlobalLayoutListener(this);
} else {
obs.removeGlobalOnLayoutListener(this);
}
}
});
setData();
return rootView;
}
public static ApodViewFragment newInstance(APOD apodElement, int position) {
ApodViewFragment fragment = new ApodViewFragment();
fragment.mApodElement = apodElement;
return fragment;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void saveData(APOD apodElement) {
}
#Override
public void readData() throws IOException {
}
private void setData() {
if(mApodElement.getMedia_type().equals("video")){
Picasso.with(getActivity()).load(R.drawable.videoplaceholder).into(mApodImageView);
}else{
Picasso.with(getActivity()).load(mApodElement.getUrl()).into(mApodImageView);
}
mTextView.setText(mApodElement.getExplanation());
mTitle.setText(mApodElement.getTitle());
}
private void setHeroImageMaxHeight(){
int screenHeight = ImageHelper.getDisplayHeight(getActivity());
mToolbar.getLayoutParams().height = screenHeight - mContentFl.getHeight();
mToolbar.requestLayout();
}
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int offset) {
float minimalTextSize = getActivity().getResources().getDimensionPixelSize(R.dimen.apod_view_title_scrolling_text_size);
float maximumTextSize = getActivity().getResources().getDimensionPixelSize(R.dimen.apod_view_title_default_text_size);
float absolut_offset = Math.abs(offset);
float text_size_difference = maximumTextSize - minimalTextSize;
float scale = (absolut_offset) / (appBarLayout.getHeight() - absolut_offset);
if (offset < 0) {
float result = maximumTextSize - (scale * text_size_difference);
mTitle.setTextSize(FontHelper.pixelsToSp(getActivity(), result));
} else {
mTitle.setTextSize(FontHelper.pixelsToSp(getActivity(), maximumTextSize));
}
}
}
And XML layout file
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/apod_fragment_ctl"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:expandedTitleMarginStart="16dp"
android:fitsSystemWindows="true">
<ImageView
android:id="#+id/apod_view_apod_iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax"/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<RelativeLayout
android:layout_width="wrap_content"
android:fitsSystemWindows="true"
android:layout_height="wrap_content">
<TextView
android:id="#+id/apod_fragment_title_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:textSize="#dimen/apod_view_title_default_text_size"
android:layout_alignParentBottom="true"
app:layout_collapseMode="pin"
/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:background="#android:color/holo_purple"
android:fitsSystemWindows="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<FrameLayout
android:id="#+id/fragment_apod_fl"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:layout_gravity="center_vertical"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:text="TITLE"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:textAppearance="#style/TextAppearance.AppCompat.Headline"/>
<TextView
android:id="#+id/apod_view_text_tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</FrameLayout>
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
app:layout_anchor="#id/cardview"
app:layout_anchorGravity="top|right|end"
android:src="#drawable/ic_rocket_em_blank"
android:layout_margin="16dp"
app:backgroundTint="#android:color/holo_purple"
style="#style/FabStyle"/>
</android.support.design.widget.CoordinatorLayout>
I'd say that reason must be somewhere in Adapter or fragment's methods, which create new Fragment, but can't really find it. Any help appreciated, cheers!
Related
I have a Bottom Navigation Bar, and a frame layout which is the fragment container. So when a an icon on a Bottom Navigation Bar is clicked, the fragment above changes.
In one of the fragment, I have a coordinator layout, collapsing toolbar, and recycler view. At the moment, the data is just a dummy data.
The problem that I am encountering is that whenever that fragment is inflated for the first time, the Recyclerview works fine and shows all of the items in the list. But when I change the fragment and come back to this fragment again, the last item of the Recyclerview is being cut off and is being hidden behind the Bottom Navigation Bar.
Here is my code for activity_home_screen.xml
<RelativeLayout 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"
tools:context="com.smartinc.livesportstv.activities.HomeScreen">
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
app:itemBackground="?attr/colorPrimary"
app:itemIconTint="#drawable/selector_bottombar_item"
app:itemTextColor="#drawable/selector_bottombar_item"
app:menu="#menu/bottombar_menu" />
<FrameLayout
android:id="#+id/frame_fragmentholder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_nav"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
Here is the fragment_events.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fitsSystemWindows="true"
android:id="#+id/coordinator">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="120dp"
>
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:title="Events"
app:expandedTitleTextAppearance="#style/TransparentText"
app:collapsedTitleTextAppearance="#style/Toolbar_text_black"
app:collapsedTitleGravity="center_horizontal"
android:paddingEnd="20dp"
android:fitsSystemWindows="true"
>
<!-- You can add views that you want to appear on the
collapsing toolbar here -->
<TextView
android:id="#+id/events_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Events"
android:textSize="30sp"
android:textColor="#color/black"
android:layout_marginTop="30dp"
android:layout_marginStart="20dp"
android:textStyle="bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="29 March, Thursday"
android:textSize="20sp"
android:textColor="#color/grey_800"
android:layout_marginTop="70dp"
android:layout_marginStart="20dp"
/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
android:minHeight="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"
android:gravity="center_horizontal"
app:popupTheme="#style/AppTheme"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_events"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Request"
android:textSize="17sp"
android:layout_gravity="end"
android:textColor="#color/colorPrimaryDark"
android:padding="10dp"
android:layout_marginEnd="10dp"
android:layout_marginTop="5dp"
/>
Here is HomeScreen.java
public class HomeScreen extends AppCompatActivity {
private BottomNavigationView bottomNavigationView;
private String fragName = "";
#Override
public void startActivity(Intent intent) {
super.startActivity(intent);
Constants.overridePendingTransitionEnter(this);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
init();
setMainFragment();
setBottomNavigation();
}
private void init(){
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_nav);
}
private void setBottomNavigation(){
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.bottombaritem_events:
if(!fragName.equals("events")) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.left_slide_in, R.anim.right_slide_out);
ft.replace(R.id.frame_fragmentholder, new EventsFragment());
ft.commit();
fragName = "events";
}
return true;
case R.id.bottombaritem_channels:
FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
if(fragName.equals("events")) {
ft2.setCustomAnimations(R.anim.right_slide_in, R.anim.left_slide_out);
} else {
ft2.setCustomAnimations(R.anim.left_slide_in, R.anim.right_slide_out);
}
ft2.replace(R.id.frame_fragmentholder, new ChannelsFragment());
ft2.commit();
fragName = "channels";
return true;
case R.id.bottombaritem_more:
if(!fragName.equals("more")) {
FragmentTransaction ft3 = getSupportFragmentManager().beginTransaction();
ft3.setCustomAnimations(R.anim.right_slide_in, R.anim.left_slide_out);
ft3.replace(R.id.frame_fragmentholder, new MoreFragment());
ft3.commit();
fragName = "more";
}
return true;
}
return false;
}
});
}
private void setMainFragment(){
fragName = "events";
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame_fragmentholder, new EventsFragment());
ft.commit();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Constants.overridePendingTransitionExit(this);
}
}
And here is EventsFragment.java
public class EventsFragment extends Fragment {
private RecyclerView mRecyclerView;
private ArrayList<String> mData;
private CollapsingToolbarLayout collapsing_toolbar;
private Context mContext;
public EventsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_events, container, false);
mContext = getActivity();
final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) view.findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = (AppBarLayout) view.findViewById(R.id.app_bar);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = true;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbarLayout.setTitle("Events");
isShow = true;
} else if(isShow) {
collapsingToolbarLayout.setTitle(" ");//carefull there should a space between double quote otherwise it wont work
isShow = false;
}
}
});
// Initialize the RecyclerView
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_events);
setUpRecyclerView();
return view;
}
private void setUpRecyclerView() {
LinearLayoutManager llm = new LinearLayoutManager(mContext);
llm.setAutoMeasureEnabled(true);
mRecyclerView.setLayoutManager(llm);
EventsAdapter eventsAdapter = new EventsAdapter(mContext);
mRecyclerView.setAdapter(eventsAdapter);
}
}
Any help would be really appreciated. Thanks!
Remove this line from Event XML.
android:fitsSystemWindows="true"
And everything would be good to go.
override the fragment's setUserVisibleHint(),call view?.requestlayout()
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
view?.requestLayout()
super.setUserVisibleHint(isVisibleToUser)
}
collapsingToolbarLayout.setTitle("Events");
this layout is hiding your last Recycler view, when this is shown your last item is hidden, when you set
collapsingToolbarLayout.setTitle("");
your last item is visible.
So, set padding to parent layout accordingly
In my app i am using this library
https://github.com/DmitryMalkovich/circular-with-floating-action-button
to implement progress bar with floating action button. Its working on activity but when i included this layout in my fragment's layout progress bar doesn't show.
Here is my code for better explanation
Please guide me where i am going wrong
Any help will be appreciated.
customlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
>
<com.dmitrymalkovich.android.ProgressFloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:clickable="true">
<ProgressBar
android:id="#+id/progressbar"
style="#style/Widget.AppCompat.ProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/transparent_logo"
app:backgroundTint="#color/bg_color"
android:layout_centerInParent="true"
/>
</com.dmitrymalkovich.android.ProgressFloatingActionButton>
</RelativeLayout>
fragmentlayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layoutcontainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="bg_color"
>
<include
layout="#layout/customlayout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<include
layout="#layout/otherlayout
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I am hiding and showing the parent layout of customlayout.xml on runtime when i get data from serivice, before service call i SHOW it with View.VISIBLE and after service call i HIDE it with View.GONE
UPDATED
Java code
Fragment
public class MyFragment extends Fragment {
private Context context;
//root view of layout
View rootView;
private static final String ARG_PARAM1 = "Class";
private String screen_title;
private String URL = "";
public MyFragment() {
// Required empty public constructor
}
public static MyFragment newInstance(String param1) {
MyFragmentfragment = new MyFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
if (getArguments() != null) {
screen_title = getArguments().getString(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragmentlayout, container, false);
//find views by ids
getData();
return rootView;
}
private void getData() {
CustomClass.getInstance(context, rootView).show();
//service call
//on getting response from serivce (have implemented a listener here)
CustomClass.getInstance(context, rootView).hide(); }
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
CustomClass
public class CustomClass {
private ProgressBar mProgressBar;
private FloatingActionButton mFab;
private RelativeLayout parentLayout;
private LayoutInflater inflater;
private static CustomClass custom;
private CustomClass (Context context) {
findViewsById(context);
}
private CustomClass (View view) {
findViewsById(view);
}
public static CustomClass getInstance(Context context, View view) {
custom = new CustomClass (view);
custom.setPColor(context);
return custom;
}
public static CustomClass getInstance(Context context) {
custom = new CustomClass (context);
custom.setPColor(context);
return custom;
}
private void setPColor(Context context) {
if (mProgressBar != null)
mProgressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(context, R.color.bluecolor), android.graphics.PorterDuff.Mode.MULTIPLY);
}
private void findViewsById(View view) {
if (view != null) {
mProgressBar = (ProgressBar) view.findViewById(R.id.custom_progressbar);
mFab = (FloatingActionButton) view.findViewById(R.id.custom_floatingActionButton);
parentLayout = (RelativeLayout) view.findViewById(R.id.rl_progress_fab_container);
}
}
private void findViewsById(Context context) {
Activity activity = (Activity) context;
if (activity != null) {
mProgressBar = (ProgressBar) activity.findViewById(R.id.custom_progressbar);
mFab = (FloatingActionButton) activity.findViewById(R.id.custom_floatingActionButton);
parentLayout = (RelativeLayout) activity.findViewById(R.id.rl_progress_fab_container);
}
}
public void show() {
if (custom.parentLayout != null)
custom.parentLayout.setVisibility(View.VISIBLE);
}
public void hide() {
if (custom.parentLayout != null)
custom.parentLayout.setVisibility(View.GONE);
}
make your customlayout at the bottom with the parent layout.
so your z index for that layout is at the top and it will be visible and gone that can be seen by you.
You need to use CoordinatorLayout with FAB .
Just put your FAB inside CoordinatorLayout.
As you can see library sample code suggests to use it too.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.dmitrymalkovich.android.progressfabsample.ScrollingActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="#dimen/app_bar_height"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<com.dmitrymalkovich.android.ProgressFloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
android:clickable="true"
app:layout_anchor="#id/app_bar"
app:layout_anchorGravity="bottom|end">
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_backup_black_24dp"
app:backgroundTint="#color/colorFab" />
<ProgressBar
style="#style/Widget.AppCompat.ProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</com.dmitrymalkovich.android.ProgressFloatingActionButton>
<com.dmitrymalkovich.android.ProgressFloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:clickable="true">
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_backup_black_24dp"
app:backgroundTint="#color/colorFab" />
<ProgressBar
style="#style/Widget.AppCompat.ProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</com.dmitrymalkovich.android.ProgressFloatingActionButton>
try this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragmentlayout, container, false);
//find views by ids
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getData();
}
});
return rootView;
}
or
private void getData() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
CustomClass.getInstance(context, rootView).show();
CustomClass.getInstance(context, rootView).hide();
}
});
}
I have a problem with my layout. I'm trying to do something like this:
For now, i have a RecyclerView with a CardView inside it. in the CardView I have put an ImageView and a TextView but I don't know why but the CardView is more height than ImageView inside it.
Here is The code and a Sample Image.
And Here is the code: Activity
public class AddRoomActivity extends AppCompatActivity implements View.OnClickListener {
private View snackView;
private FloatingActionButton fabDoneAddRoom;
private EditText etRoomName;
private String roomName = null;
public final static String KEY_PI_IP = "MyPi_IP";
private final static String KEY_ROOM = "myRoom";
private final static String KEY_ROOM_TYPE = "myRoom_Type";
private RecyclerView typeRecyclerView;
private GridLayoutManager layoutManager;
private AddRoomActivity.TypeAdapter adapter;
private String myPi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_room);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fabDoneAddRoom = (FloatingActionButton) findViewById(R.id.doneAddRoom);
fabDoneAddRoom.setOnClickListener(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
etRoomName = (EditText) findViewById(R.id.addRoomName);
myPi = getIntent().getStringExtra(KEY_PI_IP);
layoutManager = new GridLayoutManager(this, 2);
typeRecyclerView = (RecyclerView) findViewById(R.id.recyclerTypeRoom);
typeRecyclerView.setHasFixedSize(true);
typeRecyclerView.setLayoutManager(layoutManager);
// specify an adapter (see also next example)
adapter = new TypeAdapter(getResources().getStringArray(R.array.roomTypeName));
typeRecyclerView.setAdapter(adapter);
}
void showToastMessage(String message) {
Snackbar.make(snackView, message, Snackbar.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.doneAddRoom) {
snackView = v;
String myString = etRoomName.getText().toString();
if (myString.length() > 0) {
roomName = myString.substring(0, 1).toUpperCase() + myString.substring(1);
addRoomToPi();
} else {
showToastMessage(getString(R.string.noNameRoom));
}
}
}
private void addRoomToPi() {
Integer ret = -1;
try {
ret = (Integer) new RaspberryTCPClient(myPi, getResources(), RaspberryTCPClient.TYPE_ADD_ROOM, roomName, XMLRoom.TYPE_KITCHEN_ROOM).execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (ret == RaspberryTCPClient.OPERATION_DONE) {
showToastMessage(getString(R.string.roomAdded));
Intent data = new Intent();
data.putExtra(KEY_ROOM, roomName);
setResult(Activity.RESULT_OK, data);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, 1500);
} else {
showToastMessage(getString(R.string.addRoomError));
}
}
private class TypeAdapter extends RecyclerView.Adapter<AddRoomActivity.TypeAdapter.ViewHolder> {
private String[] myData;
public TypeAdapter(String[] roomList) {
myData = roomList;
}
public void onItemClick(int position) {
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView tvType;
public CardView cvRoomCard;
public ImageView imgRoomType;
public ViewHolder(View vCard) {
super(vCard);
cvRoomCard = (CardView) vCard;
tvType = (TextView) vCard.findViewById(R.id.tvTypeName);
imgRoomType = (ImageView) vCard.findViewById(R.id.img_roomType);
}
}
#Override
public AddRoomActivity.TypeAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.type_room_recycler_view, parent, false);
// set the view's size, margins, paddings and layout parameters
//...
AddRoomActivity.TypeAdapter.ViewHolder vh = new AddRoomActivity.TypeAdapter.ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(AddRoomActivity.TypeAdapter.ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.tvType.setText(myData[position]);
switch (position) {
case XMLRoom.TYPE_ROOM:
holder.imgRoomType.setImageResource(R.drawable.img_room_sqr);
break;
case XMLRoom.TYPE_BED_ROOM:
holder.imgRoomType.setImageResource(R.drawable.img_bedroom_sqr);
break;
case XMLRoom.TYPE_GARDEN_ROOM:
holder.imgRoomType.setImageResource(R.drawable.img_garden_sqr);
break;
case XMLRoom.TYPE_KITCHEN_ROOM:
holder.imgRoomType.setImageResource(R.drawable.img_kitchen_sqr);
break;
case XMLRoom.TYPE_LIVING_ROOM:
holder.imgRoomType.setImageResource(R.drawable.img_living_room_sqr);
break;
case XMLRoom.TYPE_SWIMMING_POOL_ROOM:
holder.imgRoomType.setImageResource(R.drawable.img_swimming_pool_sqr);
break;
}
holder.cvRoomCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClick(position);
}
});
}
#Override
public int getItemCount() {
return myData.length;
}
}
The MainLayout
<android.support.design.widget.AppBarLayout
android:id="#+id/appBar"
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="#dimen/toolbar"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="90dp"
android:layout_marginTop="#dimen/toolbar"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true">
<TextView
android:id="#+id/tvAddRoom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_margin="5dp"
android:gravity="center"
android:text="#string/textAddRoom"
android:textColor="#color/primary_text"
android:textSize="20dp"
android:textStyle="bold" />
<android.support.design.widget.TextInputLayout
android:id="#+id/inputaddRoomName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tvAddRoom"
android:layout_gravity="center"
android:layout_margin="5dp">
<EditText
android:id="#+id/addRoomName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_RoomName"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerTypeRoom"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/inputaddRoomName"
android:scrollbars="vertical" />
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/doneAddRoom"
android:layout_width="#dimen/fab_Dimension"
android:layout_height="#dimen/fab_Dimension"
android:layout_gravity="bottom|center"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#drawable/ic_done" />
</android.support.design.widget.CoordinatorLayout>
and The View Layout:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp">
<ImageView
android:id="#+id/img_roomType"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:src="#drawable/img_room" />
<TextView
android:id="#+id/tvTypeName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="center"
android:textColor="#android:color/white"
android:textSize="20sp" />
</android.support.v7.widget.CardView>
Extracted required info from the accepted answer in case URL becomes invalid in future and to save time.
GridLayoutManager is used to display the RecyclerView in Grid manner instead of list.
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(mLayoutManager);
Kotlin version:
recyclerView.apply {
layoutManager = GridLayoutManager(this, 2)
}
You can use this code simply
<android.support.v7.widget.RecyclerView
app:layoutManager="android.support.v7.widget.GridLayoutManager"
app:spanCount="2"/>
With androidX libraries simply do:
<androidx.recyclerview.widget.RecyclerView
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"/>
for Horizontal recycler view, it works for me
layoutManagerSuperCategories = new GridLayoutManager(context,2,LinearLayoutManager.HORIZONTAL,false);
rv_superCategories.setLayoutManager(layoutManagerSuperCategories);
use "0dp" in layout_width and layout_height for putting views in it's position.
like this:
android:layout_width="0dp"
and use Guidelines in your xml.
<ImageView
android:id="#+id/img_roomType"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentTop="true"
android:src="#drawable/img_room" />
<TextView
android:id="#+id/tvTypeName"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="bottom"
android:gravity="center"
android:textColor="#android:color/white"
android:textSize="20sp" />
this is NOT true code, u have to use Guidelines.
I have a dialog fragment and I need to launch a fragment within this dialog fragment. This means my fragment should occupy the same window as that of dialog fragment. How do I do this? This is my dialog fragment code -
public class CallDialogFragment extends DialogFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.call_dialog_fragment, container, false);
return view;
}
}
Just use fragment transaction and add another dialog fragment. and add to back stack.
you can use coordinator layout for dialog-fragment.. when you drag layout to upper side it will be your new fragment. and when you drag to down it will be your dialog fragment.
here is the xml code..
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="#dimen/detail_backdrop_height"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:fitsSystemWindows="true"
>
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
local:contentScrim="?attr/colorPrimary"
local:expandedTitleMarginEnd="64dp"
local:expandedTitleMarginBottom="22dp"
local:expandedTitleMarginStart="20dp"
local:expandedTitleTextAppearance="#style/TextAppearance.AppCompat.Title"
local:layout_scrollFlags="scroll|exitUntilCollapsed">
<ProgressBar
android:id="#+id/progressfull"
android:visibility="visible"
android:layout_width="match_parent"
android:layout_marginTop="80dp"
android:layout_height="24dp" />
<ImageView
android:id="#+id/image_preview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
local:layout_collapseMode="parallax"
/>
<View
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
android:layout_alignBottom="#+id/image_preview"
android:background="?attr/colorPrimary"
local:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarIcon"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light"
local:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/addbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
local:borderWidth="0dp"
android:layout_marginRight="#dimen/fab_margin"
android:layout_marginLeft="#dimen/fab_margin"
android:layout_marginTop="#dimen/fab_margin"
android:layout_marginBottom="25dp"
android:src="#drawable/ic_add" />
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="fill_vertical"
android:background="#color/colorPrimaryDark"
local:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp">
<android.support.v7.widget.CardView
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
fragment_image_slider.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
here is the java code..
public class SlideshowDialogFragment extends DialogFragment {
private String TAG = SlideshowDialogFragment.class.getSimpleName();
private ArrayList<ItemCategories> images;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private String lblCount, lblTitle, lblDate;
private int selectedPosition = 0;
private CardView cardView;
private Context mContext;
public static SlideshowDialogFragment newInstance() {
SlideshowDialogFragment fragmentFullScreen = new SlideshowDialogFragment();
return fragmentFullScreen;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_image_slider, container, false);
viewPager = (ViewPager) v.findViewById(R.id.viewpager);
setHasOptionsMenu(true);
ViewCompat.setOnApplyWindowInsetsListener(viewPager,
new OnApplyWindowInsetsListener() {
#Override
public WindowInsetsCompat onApplyWindowInsets(View v,
WindowInsetsCompat insets) {
insets = ViewCompat.onApplyWindowInsets(v, insets);
if (insets.isConsumed()) {
return insets;
}
boolean consumed = false;
for (int i = 0, count = viewPager.getChildCount(); i < count; i++) {
ViewCompat.dispatchApplyWindowInsets(viewPager.getChildAt(i), insets);
if (insets.isConsumed()) {
consumed = true;
}
}
return consumed ? insets.consumeSystemWindowInsets() : insets;
}
});
images = (ArrayList<ItemCategories>) getArguments().getSerializable("images");
selectedPosition = getArguments().getInt("position");
Log.e(TAG, "position: " + selectedPosition);
Log.e(TAG, "images size: " + images.size());
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
setCurrentItem(selectedPosition);
getArguments().remove("position");
getArguments().remove("images");
return v;
}
private void setCurrentItem(int position) {
viewPager.setCurrentItem(position, false);
displayMetaInfo(selectedPosition);
}
// page change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
displayMetaInfo(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void displayMetaInfo(int position) {
lblCount = (position + 1) + " of " + images.size();
ItemCategories image = images.get(position);
lblTitle = "" + image.getCategoryItem();
lblDate = "" + image.getUrlThumb();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, R.style.MyMaterialThemeFull);
}
#Override
public void onDetach() {
super.onDetach();
}
// adapter
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.image_fullscreen_preview, container, false);
ImageView imageViewPreview = (ImageView) view.findViewById(R.id.image_preview);
Toolbar toolbarIcon = (Toolbar) view.findViewById(R.id.toolbarIcon);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbarIcon);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) view.findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = (AppBarLayout) view.findViewById(R.id.appbar);
DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int screenHeight = displaymetrics.heightPixels;
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appBarLayout.getLayoutParams();
lp.height = screenHeight;
toolbarIcon.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment prev = getActivity().getSupportFragmentManager().findFragmentByTag("slideshow");
if (prev != null) {
DialogFragment dialogFullScreen = (DialogFragment) prev;
dialogFullScreen.dismiss();
}
}
});
ItemCategories image = images.get(position);
Glide.with(getActivity()).load(image.getUrlThumb())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageViewPreview);
collapsingToolbar.setTitle(lblTitle);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View) obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
just copy this code and you will know what i am talking about
I have a layout with CollapsingToolbarLayout, a RecyclerView and a FloactingActionButton.
The idea is expand my Toolbar when the user is scrolling RecyclerView down and retracting it when scrolling up.
But when I scroll up my RecyclerView, the AppBarLayout retracts and my FloactingActionButton disappears.
I want to show it again in some other place in my screen like the botton.
How can I do It?
This is my screen:
Before Scrolling down - My FloactingActionButton is there.
After scrolling down - There's no room left for FloactingActionButton, so it dismiss. I just want to show it on botton of screen.
Code of my Layout XML :
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="192dp">
<android.support.design.widget.CollapsingToolbarLayout
android:elevation="4dp"
android:id="#+id/collapsing_toolbar"
android:background="#color/primary"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
style="#style/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
app:layout_anchor="#id/app_bar_layout"
app:layout_anchorGravity="bottom|right|end" />
Code of my Activity
public class MainActivityRecycler extends AppCompatActivity implements OnDataSelected {
private CollapsingToolbarLayout collapsingToolbarLayout;
public void onDataSelected(View view, int position) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_recycler);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle("Collapsing");
//collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.transparent));
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ArrayList<String> details = new ArrayList<String>();
details.add("Main Facilities");
details.add("Restaurants");
details.add("Shops");
details.add("Motel");
details.add("Forecourt");
DetailsAdapter mAdapter = new DetailsAdapter(this, null, details);
recyclerView.setAdapter(mAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
class DetailsAdapter extends RecyclerView.Adapter<DetailsAdapter.ViewHolder> {
private List<String> cars;
private Context context;
private OnDataSelected onDataSelected;
public DetailsAdapter(Context context, OnDataSelected onDataSelected, List<String> cars) {
this.context = context;
this.onDataSelected = onDataSelected;
this.cars = cars;
}
#Override
public DetailsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String car = cars.get(position);
holder.textViewTitleCar.setText(car);
}
#Override
public int getItemCount() {
return cars.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewTitleCar;
public ViewHolder(View view) {
super(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
treatOnDataSelectedIfNecessary(v, getAdapterPosition());
}
});
textViewTitleCar = (TextView) view.findViewById(R.id.info_text);
}
}
private void treatOnDataSelectedIfNecessary(View view, int position) {
if (onDataSelected != null) {
onDataSelected.onDataSelected(view, position);
}
}
}
}
You can easily create any behavior for your item. You will need to realize ScrollListener for your AppBarLayout. More example of custom behavoir - Github
I hope correctly understood and helped.
public class FlexibleSpaceExampleActivity extends AppCompatActivity
implements AppBarLayout.OnOffsetChangedListener {
private static final int PERCENTAGE_TO_SHOW_IMAGE = 20;
private View mFab;
private int mMaxScrollSize;
private boolean mIsImageHidden;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flexible_space);
mFab = findViewById(R.id.flexible_example_fab);
Toolbar toolbar = (Toolbar) findViewById(R.id.flexible_example_toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
onBackPressed();
}
});
AppBarLayout appbar = (AppBarLayout) findViewById(R.id.flexible_example_appbar);
appbar.addOnOffsetChangedListener(this);
}
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
if (mMaxScrollSize == 0)
mMaxScrollSize = appBarLayout.getTotalScrollRange();
int currentScrollPercentage = (Math.abs(i)) * 100
/ mMaxScrollSize;
if (currentScrollPercentage >= PERCENTAGE_TO_SHOW_IMAGE) {
if (!mIsImageHidden) {
mIsImageHidden = true;
ViewCompat.animate(mFab).scaleY(0).scaleX(0).start();
/**
* Realize your any behavior for FAB here!
**/
}
}
if (currentScrollPercentage < PERCENTAGE_TO_SHOW_IMAGE) {
if (mIsImageHidden) {
mIsImageHidden = false;
ViewCompat.animate(mFab).scaleY(1).scaleX(1).start();
/**
* Realize your any behavior for FAB here!
**/
}
}
}
public static void start(Context c) {
c.startActivity(new Intent(c, FlexibleSpaceExampleActivity.class));
}
}
Use Floating Action Button and set property as I have set. It is very easy to display FAB in collapsingToolbarLayout.
<android.support.design.widget.AppBarLayout
android:id="#+id/activity_main_appbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:ignore="InconsistentLayout">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/activity_main_collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#2196f3"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
tools:ignore="InconsistentLayout">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/paris"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="#+id/activity_main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#android:color/transparent"
app:layout_collapseMode="pin"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="#+id/activity_main_nested_scroll_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:ignore="InconsistentLayout">
<android.support.v7.widget.RecyclerView
android:id="#+id/activity_main_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:src="#drawable/ic_call_black_24dp"
app:layout_anchor="#id/activity_main_appbar"
app:layout_anchorGravity="bottom|right|end" />