Android Layout make all children's not clickable - android

I am using Relative Layout and many buttons in it with TextViews etc.I want to make all of them not clickable unless some event happens.
I tried setting RelativeLayout.setClickable(false); but still all the elements inside the layout are clickable.
I know one way of doing it that setting each child element not clickable but it is not an appropriate way because i have lot of child elements like buttons text views etc inside a layout i cannot make each child not clickable.
Here my question is How to set all to setClickable(false); in layout ??

I found an alternative way to achieve this. You may create a blocking LinearLayout on top all its sibling views in the RelativeLayout like below:
<RelativeLayout
android:id="#+id/rl_parent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- the children views begins -->
...
<!-- the children views ends -->
<LinearLayout
android:id="#+id/ll_mask"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent"
android:clickable="true"
android:orientation="horizontal"
android:visibility="visible"/>
</RelativeLayout>
Later you may toggle the LinearLayout's visibility to GONE to allow the children views to be clickable again:
mMask.setVisibility(View.VISIBLE); // blocks children
mMask.setVisibility(View.GONE); // children clickable

When you say click do you actually mean touch? Touch events are done element by element. They're first sent to the top level, which says if it handled it and if it didn't it goes onto each children of the view.
When a touch event is created, the onTouch method of view in the chain is called, if any of these return true (true meaning "I handled this!") it stops going down to the children.
To make your relativelayout block touches and clicks for all of its children you simply need to set the onTouchListener, like this:
YOUR_RELATIVE_LAYOUT.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// ignore all touch events
return true;
}
});
This will ignore all touch events happening on the relative layout (and all of its children) which includes simple touch down then release events (called clicks).

You can use following function to find all the child view and cancel click.
public void setClickable(View view) {
if (view != null) {
view.setClickable(false);
if (view instanceof ViewGroup) {
ViewGroup vg = ((ViewGroup) view);
for (int i = 0; i < vg.getChildCount(); i++) {
setClickable(vg.getChildAt(i));
}
}
}
}

A very simple and full-proof way to do it is to create a sub class and override onInterceptTouchEvent:
public class MyRelativeLayout extends RelativeLayout {
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// true if you do not want the children to be clickable.
return mShouldInterceptAllTouch;
}
}
No need to call any of the children's methods.
You can still call setOnClickListener on your myRelativeLayout object. Also, you can use the class in XMLs as if you were using a RelativeLayout

An easy Kotlin extension solution to disable/enable a view and all of it's children:
fun View.isUserInteractionEnabled(enabled: Boolean) {
isEnabled = enabled
if (this is ViewGroup && this.childCount > 0) {
this.children.forEach {
it.isUserInteractionEnabled(enabled)
}
}
}
and call it with:
view.isUserInteractionEnabled(false)

If you want the children of a ViewGroup to be unresponsive to touch events, but you want the ViewGroup itself to respond to clicks, for example, you can create your own ViewGroup subclass, override onInterceptTouchEvent(), and always return true. This will intercept all touch events before children see them, while allowing your custom ViewGroup to remain responsive to touch events.
So, instead of RelativeLayout, you could use your own subclass:
public class ControlFreakRelativeLayout extends RelativeLayout {
private boolean mWithholdTouchEventsFromChildren;
// Constructors omitted for sake of brevity
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return mWithholdTouchEventsFromChildren || super.onInterceptTouchEvent(ev);
}
public void setWithholdTouchEventsFromChildren(boolean withholdTouchEventsFromChildren) {
mWithholdTouchEventsFromChildren = withholdTouchEventsFromChildren;
}
}

Problem : same as original question, but different use case. i want to progressBar widget which in container with transparent background colors. i want to disable all clicks on other items which comes under my transparent background color .
solution : just set your container clickable in my case Relative layout, it can any other layout too, keep your layout clickable true, until you want according to condition in my case till api call completed. after it simply set your parent clickable false.
android xml
<RelativeLayout
android:id="#+id/rl_parent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- the children views begins -->
...
<!-- the children views ends -->
</RelativeLayout>
Java:
rl_parent.setClickable(true); // when to disable all clicks of children view
rl_parent.setClickable(false); // when to enable all clicks of children view

Since you are going to perform the click for some items in the layout when that particular function is executed,
You can keep a static flag like a boolean
Create a static boolean globally and declare it as false, once the particular function is performed change it to true.
so in all the onclick functions that u r performing check this flag if it is true perform the necessory function.

You can make a common method in which you can write the code for disabling all your views inside your relative layout and call this method in onCreate() and then you can enable your particular view inside the the layout on your event.

If Butterknife library is used, the views can be grouped and the functionality can be done on the group.
Refer http://jakewharton.github.io/butterknife/,
#BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
List<EditText> nameViews;
The apply method allows you to act on all the views in a list at once.
ButterKnife.apply(nameViews, DISABLE);
ButterKnife.apply(nameViews, ENABLED, false);
Action and Setter interfaces allow specifying simple behavior.
static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {
#Override public void apply(View view, int index) {
view.setEnabled(false);
}
};
static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() {
#Override public void set(View view, Boolean value, int index) {
view.setEnabled(value);
}
};
For eg., if the textviews are grouped, you could do
static final ButterKnife.Setter<TextView, Boolean> ENABLED = new ButterKnife.Setter<TextView, Boolean>() {
#Override public void set(TextView view, Boolean value, int index) {
view.setClickable(value);
view.setLongClickable(value);
if(value){
view.setTextColor(color);
} else {
view.setTextColor(color);
}
}
};

As an alternative way, you can make clickable ViewGroup with children views via FrameLayout instead of RelativeLayout. Just position your child views in FrameLayout using paddings and gravity, make FrameLayout clickable, and all children views non-clickable:
<FrameLayout
android:layout_width="51dp"
android:layout_height="59dp"
android:layout_gravity="center"
android:clickable="true"
android:focusable="true"
android:onClick="#{() -> activity.onClick()}"
android:padding="5dp">
<android.support.v7.widget.AppCompatImageButton
android:layout_width="wrap_content"
android:layout_height="29dp"
android:layout_gravity="center"
android:clickable="false"
app:srcCompat="#drawable/ic_back" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|left"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:clickable="false"
android:text="#string/back" />
</FrameLayout>

I would recommend creating an extension function something like extensions.kt
import android.view.View
fun View.disable() {
isEnabled = false
isClickable = false
alpha = 0.5F
}
fun View.enable() {
isEnabled = true
isClickable = true
alpha = 1F
}
obviously, you can customize the value as you need
and now you can use it on any View like
somethingView.enable()
imageView.disable()
myButton.enable()
textView.diable()

loop on your buttons and use setClickable function and pass false value for it.
then when your even happen loop again on ot and setClickable to true

Related

Allow BottomSheet to slide up after threshold is reached on an area outside

I am trying to replicate a behavior that the current Google Maps has which allows the bottom sheet to be revealed when sliding up from the bottom bar.
Notice in the recording below that I first tap on one of the buttons at the bottom bar and then slide up, which in turn reveals the sheet behind it.
I cannot find anywhere explained how something like this can be achieved. I tried exploring the BottomSheetBehavior and customizing it, but nowhere I can find a way to track the initial tap and then let the sheet take over the movement once the touch slop threshold is reached.
How can I achieve this behavior without resorting to libraries? Or are there any official Google/Android views that allow this behavior between two sections (the navigation bar and bottom sheet)?
Took some time but I found a solution based on examples and discussion provided by two authors, their contributions can be found here:
https://gist.github.com/davidliu/c246a717f00494a6ad237a592a3cea4f
https://github.com/gavingt/BottomSheetTest
The basic logic is to handle touch events in onInterceptTouchEvent in a custom BottomSheetBehavior and check in a CoordinatorLayout if the given view (from now on named proxy view) is of interest for the rest of the touch delegation in isPointInChildBounds.
This can be adapted to use more than one proxy view if needed, the only change necessary for this is to make a proxy view list and iterate the list instead of using a single proxy view reference.
Below follows the code example of this implementation. Do note that this is only configured to handle vertical movements, if horizontal movements are necessary then adapt the code to your need.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<com.example.tabsheet.CustomCoordinatorLayout
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/customCoordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#android:color/darker_gray">
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/ic_launcher_background"
android:text="Tab 1" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/ic_launcher_background"
android:text="Tab 2" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/ic_launcher_background"
android:text="Tab 3" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/ic_launcher_background"
android:text="Tab 4" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/ic_launcher_background"
android:text="Tab 5" />
</com.google.android.material.tabs.TabLayout>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="#+id/bottomSheet"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3F51B5"
android:clipToPadding="false"
app:behavior_peekHeight="0dp"
app:layout_behavior=".CustomBottomSheetBehavior" />
</com.example.tabsheet.CustomCoordinatorLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
final CustomCoordinatorLayout customCoordinatorLayout;
final CoordinatorLayout bottomSheet;
final TabLayout tabLayout;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customCoordinatorLayout = findViewById(R.id.customCoordinatorLayout);
bottomSheet = findViewById(R.id.bottomSheet);
tabLayout = findViewById(R.id.tabLayout);
iniList(bottomSheet);
customCoordinatorLayout.setProxyView(tabLayout);
}
private void iniList(final ViewGroup parent) {
#ColorInt int backgroundColor;
final int padding;
final int maxItems;
final float density;
final NestedScrollView nestedScrollView;
final LinearLayout linearLayout;
final ColorDrawable dividerDrawable;
int i;
TextView textView;
ViewGroup.LayoutParams layoutParams;
density = Resources.getSystem().getDisplayMetrics().density;
padding = (int) (20 * density);
maxItems = 50;
backgroundColor = ContextCompat.getColor(this, android.R.color.holo_blue_bright);
dividerDrawable = new ColorDrawable(Color.WHITE);
layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
nestedScrollView = new NestedScrollView(this);
nestedScrollView.setLayoutParams(layoutParams);
nestedScrollView.setClipToPadding(false);
nestedScrollView.setBackgroundColor(backgroundColor);
linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(layoutParams);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
linearLayout.setDividerDrawable(dividerDrawable);
for (i = 0; i < maxItems; i++) {
textView = new TextView(this);
textView.setText("Item " + (1 + i));
textView.setPadding(padding, padding, padding, padding);
linearLayout.addView(textView, layoutParams);
}
nestedScrollView.addView(linearLayout);
parent.addView(nestedScrollView);
}
}
CustomCoordinatorLayout.java
public class CustomCoordinatorLayout extends CoordinatorLayout {
private View proxyView;
public CustomCoordinatorLayout(#NonNull Context context) {
super(context);
}
public CustomCoordinatorLayout(
#NonNull Context context,
#Nullable AttributeSet attrs
) {
super(context, attrs);
}
public CustomCoordinatorLayout(
#NonNull Context context,
#Nullable AttributeSet attrs,
int defStyleAttr
) {
super(context, attrs, defStyleAttr);
}
#Override
public boolean isPointInChildBounds(
#NonNull View child,
int x,
int y
) {
if (super.isPointInChildBounds(child, x, y)) {
return true;
}
// we want to intercept touch events if they are
// within the proxy view bounds, for this reason
// we instruct the coordinator layout to check
// if this is true and let the touch delegation
// respond to that result
if (proxyView != null) {
return super.isPointInChildBounds(proxyView, x, y);
}
return false;
}
// for this example we are only interested in intercepting
// touch events for a single view, if more are needed use
// a List<View> viewList instead and iterate in
// isPointInChildBounds
public void setProxyView(View proxyView) {
this.proxyView = proxyView;
}
}
CustomBottomSheetBehavior.java
public class CustomBottomSheetBehavior<V extends View> extends BottomSheetBehavior<V> {
// we'll use the device's touch slop value to find out when a tap
// becomes a scroll by checking how far the finger moved to be
// considered a scroll. if the finger moves more than the touch
// slop then it's a scroll, otherwise it is just a tap and we
// ignore the touch events
private int touchSlop;
private float initialY;
private boolean ignoreUntilClose;
public CustomBottomSheetBehavior(
#NonNull Context context,
#Nullable AttributeSet attrs
) {
super(context, attrs);
touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
#Override
public boolean onInterceptTouchEvent(
#NonNull CoordinatorLayout parent,
#NonNull V child,
#NonNull MotionEvent event
) {
// touch events are ignored if the bottom sheet is already
// open and we save that state for further processing
if (getState() == STATE_EXPANDED) {
ignoreUntilClose = true;
return super.onInterceptTouchEvent(parent, child, event);
}
switch (event.getAction()) {
// this is the first event we want to begin observing
// so we set the initial value for further processing
// as a positive value to make things easier
case MotionEvent.ACTION_DOWN:
initialY = Math.abs(event.getRawY());
return super.onInterceptTouchEvent(parent, child, event);
// if the last bottom sheet state was not open then
// we check if the current finger movement has exceed
// the touch slop in which case we return true to tell
// the system we are consuming the touch event
// otherwise we let the default handling behavior
// since we don't care about the direction of the
// movement we ensure its difference is a positive
// integer to simplify the condition check
case MotionEvent.ACTION_MOVE:
return !ignoreUntilClose
&& Math.abs(initialY - Math.abs(event.getRawY())) > touchSlop
|| super.onInterceptTouchEvent(parent, child, event);
// once the tap or movement is completed we reset
// the initial values to restore normal behavior
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
initialY = 0;
ignoreUntilClose = false;
return super.onInterceptTouchEvent(parent, child, event);
}
return super.onInterceptTouchEvent(parent, child, event);
}
}
Result with transparent status bar and navigation bar to help visualize the bottom sheet sliding up, but excluded from the code above since it was not relevant for this question.
Note: It is possible you might not even need a custom bottom sheet behavior if your bottom sheet layout contains a certain scrollable view type (NestedScrollView for example) that can be used as is by the CoordinatorLayout, so try without the custom bottom sheet behavior once your layout is ready since it will make this simpler.
You could try something like this (It's Pseudocode, hopefully you understand what I'm getting at):
<FrameLayout id="+id/bottomSheet">
<View id="exploreNearby bottomMargin="buttonContainerHeight/>
<LinearLayout>
<Button id="explore"/>
<Button id="explore"/>
<Button id="explore"/>
</LinearLayout>
<View width="match" height="match" id="+id/touchCatcher"
</FrameLayout>
Add a gesture detector on the bottomSheet view on override onTouch(). which uses SimpleOnGestureListener to wait for a "scroll" events - everything but a scroll event you can replicate down through to the view as normal.
On a scroll event you can grow your exploreNearby as a delta (make sure it doesn't recurse or go to high or too low).
The Bottom sheet class will already do this for you. Just set it's peek height to 0 and it should already listen for the slide up gesture.
However, I'm not positive it will work with a peek height of 0. So if that doesn't work, simply put a peek height of 20dp and make the top portion of the bottom sheet layout transparent so it is not visible.
That should do the trick for ya, unless I'm misunderstanding your question. If your goal is to simply be able to tap at the bottom and slide upwards bringing up the bottom sheet that should be pretty straight forward.
The one possible issue that you "could" encounter is if the bottom sheet doesn't receive the touch events due to the button already consuming it. If this happens you will need to create a touch handler for the whole screen and return "true" that you are handling it each time, then simply forward the touch events to the underlying view, so when you get above the threshold of your bottom tab bar you start sending the touch events to the bottom sheet layout instead of the tab bar.
It sounds harder than it is. Most classes have an onTouch and you just forward it on. However, only go that route, if it doesn't work for you out of the box the way I described in the first two scenarios.
Lastly, one other option that might work is to create your tab buttons as part of the bottomSheetLayout and make the peek height equivalent of the tab bar. Then make sure the tab bar is constrained to bottomsheet parent bottom, so that when you swipe up it simply stays at the bottom. This would enable you to click the buttons or get the free bottom sheet behavior.
Happy Coding!

Espresso: How do I scroll to an item in a HorizontalScrollView by index?

This is what my HorizontalScrollView looks like:
<HorizontalScrollView
android:layout_below="#id/saved_circuits_title"
android:id="#+id/saved_circuits_scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:id="#+id/saved_circuits_scroll"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
In my HomeActivity I have the following relevant code that populates the HorizontalScrollView with bitmaps
onCreate{
...
this.savedCircuitsScroll = (LinearLayout) findViewById(R.id.saved_circuits_scroll);
...
}
updateSavedCircuits(){
...// code to make an ImageView from a retrieved bitmap
newImageImage.setOnClickListener(this.thumbnailListener);
this.savedCircuitsScroll.addView(newImageImage);
...
}
How do I use Espresso to scroll to an ImageView at a specified index in my HorizontalScrollView and click it?
What I've tried
I do not have ID's in my layout xml so an approach such as this does not work:
onView( withId( R.id.button)).perform( scrollTo(), click());
I know you can click on an item by index in a RecyclerView and tried finding an analogous approach for HorizontalScrollViews:
onView(withId(R.id.saved_circuits_scroll))
.perform(HorizontalScrollViewActions.actionOnItemAtPosition(0, click()));
Except HorizontalScrollViewActions does not exist.
or following this blog I tried the following to at least click an item in the HorizontalScrollView at a specified index:
// Click item at position 3
onView(withHorizontalScrollView(R.id.scroll_view).atPosition(3)).perform(click());
// Convenience helper
public static HorizontalScrollViewMatcher withHorizontalScrollView(final int horizontalScrollViewId) {
return new HorizontalScrollViewMatcher(horizontalScrollId);
}
except HorizontalScrollViewMatcher does not exist.
What do we do for HorizontalScrollView? It isn't a descendant of ScrollView so the answer here suggests I need to implement my own custom ViewAction. All I want to do is scroll to an item in a HorizontalScrollView by index and click it. Is this really needed? If this is what I need to do, how do I go about implementing this custom ViewAction?
In my case I got it by using:
onView(allOf(withId(R.id.itemTextView), withEffectiveVisibility(Visibility.VISIBLE), withText(R.string.categories))).perform(scrollTo(), click())
R.id.itemTextView is a TextView (with text R.string.categories) added dynamically to the LinearLayout:
<HorizontalScrollView>
<LinearLayout>
... [child added dynamically]
</LinearLayout>
</HorizontalScrollView>
Try to add this matcher.
public static Matcher<View> withIdAndParentId(final int viewId, final int parentId) {
Assert.assertTrue(viewId != -1);
Assert.assertTrue(parentId != -1);
return new TypeSafeMatcher<View>() {
#Override
public void describeTo(Description description) {
}
#Override
public boolean matchesSafely(View view) {
return view.getId() == viewId && isThereParentWithIdInHierarchy(view);
}
private boolean isThereParentWithIdInHierarchy(View view) {
ViewParent viewParent = view.getParent();
if (viewParent == null || !(viewParent instanceof ViewGroup))
return false;
ViewGroup parent = (ViewGroup) viewParent;
return parent.getId() == parentId || isThereParentWithIdInHierarchy(parent);
}
};
}
This is the way to use it :
onView(withIdAndParentId(R.id.YOUR_PARTICULAR_VIEW_ID, R.id.horizontalScrollViewId)).perform(scrollTo(), click());
Hope, it helps.
OK so in my particular case I found out that my scroll views had no ID associated with them (or none that I could reach reasonably, hence I couldn't use Mody's answer). However, they did have a tag associated with them so I could use Espresso's withTagValue ViewMatcher instead. Each view was associated with a circuitProject object (of course for you it may be different). And I have access to the following:
ArrayList<CircuitProject> circuitProjects = new ArrayList<>();
The index of a circuitProject object happens to be the position of the associated view in the HorizontalScrollView. The tag is the folder the circuitProject object is saved to. From here it is straightforward to get the behaviour I need with Espresso scrolling to a particular index in the HorizontalScrollView:
onView(withTagValue(withStringMatching(circuitProject.getFolderID()))).perform(scrollTo(), click());

How to make a set of views invisible in android

I'm trying to make a set of views (that include several textviews and buttons - all in different parent layouts, but in the same activity) invisible if a particular condition is evaluated to false.
The conventional way to do that would be:
findViewById(R.id.myview).setVisibility(View.INVISIBLE);
My question is, will I have to do this for all the views one by one that I want to be invisible, And then toggle them back when I want them visible?
Or, is there a way to avoid the code-repetition?
If the Views are in different parents , you can't do it directly, but you can implement a method to change the visibility of a bunch of Views if you want to keep your code clean:
List<View> relatedViews = new ArrayList<>();
// ...
relatedViews.add(view1);
relatedViews.add(view2);
relatedViews.add(view3);
// ...
changeVisibility(relatedViews, View.INVISIBLE);
// ...
private void changeVisibility(List<View> views, int visibility) {
for (View view : views) {
view.setVisibility(visibility);
}
}
As a side note, you may want to change the visibility to View.GONE instead of View.INVISIBLE so it doesn't take any space in the layout.
you can use something like this. It's not the most elegant solution but works.
The idea is give to each view that you want to hide a same content description, because in the same layout you can not use same id for multiple view. With the same content description you can find all views in your layout and hide them.
That's an example considering the first layout as Linear. You can change obviously ;)
public class TestActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
LinearLayout rootLayout = (LinearLayout)findViewById(R.id.rootLayout);
int childcount = rootLayout.getChildCount();
for (int i=0; i < childcount; i++){
View v = rootLayout.getChildAt(i);
if(v.getContentDescription() != null && v.getContentDescription().equals("invisibleView")){
v.setVisibility(View.INVISIBLE);
//I suggest you to use GONE instead of INVISIBLE to remove the space of the view
}
}
}
}
in your xml give to the object that you want to hide this property
android:contentDescription="invisibleView"
Use varargs method for show or hide multiple views.
for example if you have views like view1, view2.....etc
then just call setVisibility(View.VISIBLE,view1,view2)
public static void setVisibility(int visibility, View... views){
for (View view : views){
view.setVisibility(visibility);
}
}

Disable Scrolling in child Recyclerview android

I have a layout consists of a Parent RecyclerView with a sub Recyclerview in it
i know that it is not good to put a list inside another list but i have to so that i can use the sub list features like swiping and drag and drop
My issue is that the child Recyclerview gain focus and stops the parent from scrolling if the touch point was on it
simply i want if the touch was vertically on the child Recyclerview
the parent scrolls up and down and if the touch was horizontal or a click then the child Recyclerview list item swipes left and right.
Any help to achieve this?
I finally found a solution.
Create Custom LinearLayoutManager
public class CustomLinearLayoutManager extends LinearLayoutManager {
public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
// it will always pass false to RecyclerView when calling "canScrollVertically()" method.
#Override
public boolean canScrollVertically() {
return false;
}
}
Then instantiate it like this for vertical scrolling
CustomLinearLayoutManager customLayoutManager = new CustomLinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
Finally set the custom layout as layout manager of recycler view
recyclerView.setLayoutManager(customLayoutManager);
android:nestedScrollingEnabled="false" in the child RecyclerView
You can add
android:nestedScrollingEnabled="false"
to your RecyclerView in XML or
childRecyclerView.setNestedScrollingEnabled(false);
to your RecyclerView in Java.
EDIT:-
childRecyclerView.setNestedScrollingEnabled(false); will work only in android_version>21 devices. to work in all devices use the following
ViewCompat.setNestedScrollingEnabled(childRecyclerView, false);
On your ActivityName.java, inside the onCreate() method write:
RecyclerView v = (RecyclerView) findViewById(R.id.your_recycler_view_id);
v.setNestedScrollingEnabled(false);
By any means, if you are using Coordinator Layout, In case you want to simplify things, and you want to disable nested scrolling.
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v7.widget.RecyclerView
android:id="#+id/activitiesListRV"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.v4.widget.NestedScrollView>
And again you apply the same principle:
On your ActivityName.java, inside the onCreate() method write:
RecyclerView v = (RecyclerView) findViewById(R.id.your_recycler_view_id);
v.setNestedScrollingEnabled(false);
So basically in XML, you have to specify the app: layout_behavior
app:layout_behavior="#string/appbar_scrolling_view_behavior">
While it might not be good practice to have embedded recycler views, sometimes you cannot avoid it. Something like this might work:
public class NoScrollRecycler extends RecyclerView {
public NoScrollRecycler(Context context){
super(context);
}
public NoScrollRecycler(Context context, AttributeSet attrs){
super(context, attrs);
}
public NoScrollRecycler(Context context, AttributeSet attrs, int style){
super(context, attrs, style);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev){
//Ignore scroll events.
if(ev.getAction() == MotionEvent.ACTION_MOVE)
return true;
//Dispatch event for non-scroll actions, namely clicks!
return super.dispatchTouchEvent(ev);
}
}
This will disable the scroll event, but not the click events. Use this class for the "child" RecyclerView. You want the PARENT recyclerview to scroll, but not the child. Well this should do that, since the parent will just be the standard RecyclerView, but the child will be this custom one with no scrolling, but handles clicks. Might need to disable clicking for the parent RecyclerView.. Not sure as I have not tested this, so consider it just an example...
Also, to use this in XML (incase you didn't know) do the following:
<com.yourpackage.location.NoScrollRecycler
...
... >
...
...
</com.yourpackage.location.NoScrollRecycler>
you can use setNestedScrollingEnabled(false); on sub RecyclerView which stops scrolling inside sub RecyclerView.
In my case code was
mInnerRecyclerView.setNestedScrollingEnabled(false); where mInnerRecyclerView being inner RecyclerView.
Ithink I'm too late but here i found the solution if it's still annoying someone:
RecyclerView v = (RecyclerView);
findViewById(R.id.your_recycler_view_id);
v.setNestedScrollingEnabled(false);
sensorsRecyclerView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
I've tried many suggested solutions and couldn't find one that worked in my case. I have more than 1 RecyclerView inside a ScrollView using a GridLayoutManager. The result from the suggestion above resulted in the ScrollView stopping to scroll whenever I lifted my finger (it didn't glide to the top or bottom of the view when my finger was lifted over a RecyclerView)
Looking through the RecyclerView source, inside the onTouchEvent there is a call to the layout manager:
final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
final boolean canScrollVertically = mLayout.canScrollVertically();
If you override these in a custom layout manager, return false and it will stop scrolling. It also fixes the problem where the ScrollView would stop scrolling abruptly.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv"
android:layout_marginTop="2dp"
android:layout_marginLeft="2dp"
android:layout_marginBottom="10dp"
android:layout_marginRight="2dp"
android:nestedScrollingEnabled="false"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
put the code inside LinearLayout...no need to do anything pragmatically
If you don't want make a custom view, another option is to create a same sized layout in front of the RecyclerView, and make it clickable.
EDIT:
But unfortunately it blocks events for list item too.
The Kotlin way:
recyclerView.layoutManager = object: LinearLayoutManager(recyclerView.context) {
override fun canScrollVertically(): Boolean {
return false
}
}

Animate view from outside of bounds to show partly then full

I am currently struggling to find a good way how to animate some views in a specific way.
Following screenshots should show what I want to achieve:
First state (HIDDEN):
Second state (COLLAPSED)
Third state (EXPANDED)
The change between these states should be animated.
Those views are not draggable or slideable at all.
I know that there is the SlidingUpPanel by umano but I think that would be kind of an overkill.
At the moment the way I achieve this behaviour is the following:
I wrap the 2 panels (top and bot) in a relative layout and use the property animator to animate a change of the height of the relative layout.
So when the state is COLLAPSED then the height of the relative layout will be animated from 0 to the height of the top panel.
This works fine but I think that this is a really bad way to do this.
I already tried out to create a custom ViewGroup but the animating part didnt work yet.
Any input is appreciated.
I would use FrameLayout here as follows:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/screen"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<FrameLayout
android:id="#+id/top_panel"
android:layout_width="match_parent"
android:layout_height="#dimen/top_panel_height"
android:layout_gravity="bottom"/>
<FrameLayout
android:id="#+id/bottom_panel"
android:layout_width="match_parent"
android:layout_height="#dimen/bottom_panel_height"
android:layout_gravity="bottom"/>
</FrameLayout>
Then, create enum for states
enum State {
HIDDEN {
#Override
public void moveTo(View topPanel, View bottomPanel, long animationDuration) {
topPanel.animate().translationY(topPanel.getHeight()).setDuration(animationDuration);
bottomPanel.animate().translationY(topPanel.getHeight() + bottomPanel.getHeight()).setDuration(animationDuration);
}
},
COLLAPSED {
#Override
public void moveTo(View topPanel, View bottomPanel, long animationDuration) {
topPanel.animate().translationY(0).setDuration(animationDuration);
bottomPanel.animate().translationY(bottomPanel.getHeight()).setDuration(animationDuration);
}
},
EXPANDED {
#Override
public void moveTo(View topPanel, View bottomPanel, long animationDuration) {
topPanel.animate().translationY(-bottomPanel.getHeight()).setDuration(animationDuration);
bottomPanel.animate().translationY(0).setDuration(animationDuration);
}
};
public abstract void moveTo(View topPanel, View bottomPanel, long animationDuration);
}
Usage of this would be as follows:
State newState = State.EXPANDED;
newState.moveTo(topPanel, bottomPanel, 200);

Categories

Resources