RSS

Most votes on android-layout questions 4

Most votes on android-layout questions 4. #31 RecyclerView: Inconsistency detected. Invalid item position #32 how to change color of textview hyperlink? #33 Android list view inside a scroll view #34 How to change the color of a CheckBox? #35 How to set layout_weight attribute dynamically from code? #36 Android: How to create a Dialog without a title? #37 How to animate RecyclerView items when they appear #38 Android LinearLayout Gradient Background #39 Add padding on view programmatically #40 Avoid passing null as the view root (need to resolve layout parameters on the inflated layout's root element)

Read all the top votes questions and answers in a single page.

#31: RecyclerView: Inconsistency detected. Invalid item position (Score: 305)

Created: 2015-05-13 Last updated: 2019-08-07

Tags: android, android-layout, android-recyclerview, screen-rotation

Our QA has detected a bug: when rotating the Android device (Droid Turbo), the following RecyclerView-related crash happened:

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 2(offset:2).state:3

To me, it looks like an internal error inside RecyclerView, as I can’t think of any way of this being caused directly by our code…

Has anyone encountered this problem?

What would be the solution?

A brutal workaround could be perhaps to catch the exception when it happens and re-create the RecyclverView instance from scratch, to avoid getting left with a corrupted state.

But, if possible, I would like to understand the problem better (and perhaps fix it at its source), instead of masking it.

The bug is not easy to reproduce, but it is fatal when it happens.

The full stack-trace:

W/dalvikvm( 7546): threadid=1: thread exiting with uncaught exception (group=0x41987d40)
	E/AndroidRuntime( 7546): FATAL EXCEPTION: main
	E/AndroidRuntime( 7546): Process: com.oblong.mezzedroid, PID: 7546
	E/AndroidRuntime( 7546): java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 2(offset:2).state:3
	E/AndroidRuntime( 7546): 	at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3382)
	E/AndroidRuntime( 7546): 	at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3340)
	E/AndroidRuntime( 7546): 	at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1810)
	E/AndroidRuntime( 7546): 	at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1306)
	E/AndroidRuntime( 7546): 	at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1269)
	E/AndroidRuntime( 7546): 	at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:523)
	E/AndroidRuntime( 7546): 	at org.liboid.recycler_view.RecyclerViewContainer$LiLinearLayoutManager.onLayoutChildren(RecyclerViewContainer.java:179)
	E/AndroidRuntime( 7546): 	at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:1942)
	E/AndroidRuntime( 7546): 	at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:2237)
	E/AndroidRuntime( 7546): 	at org.liboid.recycler_view.LiRecyclerView.onLayout(LiRecyclerView.java:30)
	E/AndroidRuntime( 7546): 	at android.view.View.layout(View.java:14946)
	E/AndroidRuntime( 7546): 	at android.view.ViewGroup.layout(ViewGroup.java:4651)
	E/AndroidRuntime( 7546): 	at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
	E/AndroidRuntime( 7546): 	at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
	E/AndroidRuntime( 7546): 	at android.view.View.layout(View.java:14946)
	E/AndroidRuntime( 7546): 	at android.view.ViewGroup.layout(ViewGroup.java:4651)
	E/AndroidRuntime( 7546): 	at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
	E/AndroidRuntime( 7546): 	at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
	E/AndroidRuntime( 7546): 	at android.view.View.layout(View.java:14946)
	E/AndroidRuntime( 7546): 	at android.view.ViewGroup.layout(ViewGroup.java:4651)
	E/AndroidRuntime( 7546): 	at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
	E/AndroidRuntime( 7546): 	at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
	E/AndroidRuntime( 7546): 	at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
	E/AndroidRuntime( 7546): 	at com.oblong.mezzedroid.workspace.content.bins.BinsContainerLayout.onLayout(BinsContainerLayout.java:22)
	E/AndroidRuntime( 7546): 	at android.view.View.layout(View.java:14946)
	E/AndroidRuntime( 7546): 	at android.view.ViewGroup.layout(ViewGroup.java:4651)
	E/AndroidRuntime( 7546): 	at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
	E/AndroidRuntime( 7546): 	at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
	E/AndroidRuntime( 7546): 	at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
	E/AndroidRuntime( 7546): 	at android.view.View.layout(View.java:14946)
	E/AndroidRuntime( 7546): 	at android.view.ViewGroup.layout(ViewGroup.java:4651)
	E/AndroidRuntime( 7546): 	at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
	E/AndroidRuntime( 7546): 	at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
	E/AndroidRuntime( 7546): 	at android.view.View.layout(View.java:14946)
	E/AndroidRuntime( 7546): 	at android.view.ViewGroup.layout(ViewGroup.java:4651)
	E/AndroidRuntime( 7546): 	at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
	E/AndroidRuntime( 7546): 	at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
	E/AndroidRuntime( 7546): 	at android.view.View.layout(View.java:14946)
	E/AndroidRuntime( 7546): 	at android.view.ViewGroup.layout(ViewGroup.java:4651)
	E/AndroidRuntime( 7546): 	at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
	E/AndroidRuntime( 7546): 	at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
	E/AndroidRuntime( 7546): 	at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
	E/AndroidRuntime( 7546): 	at android.view.View.layout(View.java:14946)
	E/AndroidRuntime( 7546): 	at android.view.ViewGroup.layout(ViewGroup.java:4651)
	E/AndroidRuntime( 7546): 	at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
	E/AndroidRuntime( 7546): 	at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
	E/AndroidRuntime( 7546): 	at android.view.View.layout(View.java:14946)
	E/AndroidRuntime( 7546): 	at android.view.ViewGroup.layout(ViewGroup.java:4651)
	E/AndroidRuntime( 7546): 	at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
	E/AndroidRuntime( 7546): 	at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
	E/AndroidRuntime( 7546): 	at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
	E/AndroidRuntime( 7546): 	at android.view.View.layout(View.java:14946)
	E/AndroidRuntime( 7546): 	at android.view.ViewGroup.layout(ViewGroup.java:4651)
	E/AndroidRuntime( 7546): 	at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
	E/AndroidRuntime( 7546): 	at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
	E/AndroidRuntime( 7546): 	at android.view.View.layout(View.java:14946)
	E/AndroidRuntime( 7546): 	at android.view.ViewGroup.layout(ViewGroup.java:4651)
	E/AndroidRuntime( 7546): 	at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2132)
	E/AndroidRuntime( 7546): 	at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1872)
	E/AndroidRuntime( 7546): 	at andro

#31 Best answer 1 of RecyclerView: Inconsistency detected. Invalid item position (Score: 236)

Created: 2015-11-29 Last updated: 2019-03-26

I had a (possibly) related issue - entering a new instance of an activity with a RecyclerView, but with a smaller adapter was triggering this crash for me.

RecyclerView.dispatchLayout() can try to pull items from the scrap before calling mRecycler.clearOldPositions(). The consequence being is that it was pulling items from the common pool that had positions higher than the adapter size.

Fortunately, it only does this if PredictiveAnimations are enabled, so my solution was to subclass GridLayoutManager (LinearLayoutManager has the same problem and ‘fix’), and override supportsPredictiveItemAnimations() to return false :

/**
 * No Predictive Animations GridLayoutManager
 */
private static class NpaGridLayoutManager extends GridLayoutManager {
	/**
     * Disable predictive animations. There is a bug in RecyclerView which causes views that
     * are being reloaded to pull invalid ViewHolders from the internal recycler stack if the
     * adapter size has decreased since the ViewHolder was recycled.
     */
	@Override
	public boolean supportsPredictiveItemAnimations() {
        return false;
	}

	public NpaGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
	}

	public NpaGridLayoutManager(Context context, int spanCount) {
        super(context, spanCount);
	}

	public NpaGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) {
        super(context, spanCount, orientation, reverseLayout);
	}
}

#31 Best answer 2 of RecyclerView: Inconsistency detected. Invalid item position(Score: 92)

Created: 2016-05-09

In my case (delete/insert data in my data structure) I needed to clear recycle pool and then notify data set changed!

mRecyclerView.getRecycledViewPool().clear(); mAdapter.notifyDataSetChanged();

See also original question in stackoverflow

Created: 2011-07-20 Last updated: 2016-01-04

Tags: android, android-layout

I am using this code for hyperlink:

<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:id="@+id/hyperlink" 
    android:text="@string/hyperlink"
    android:autoLink="web"/>

By default it is showing blue color, but how do I change color of hyperlink in Android?

Created: 2011-07-20

Add android:textColorLink="yourcolorhere" to your TextView

#32 Best answer 2 of how to change color of textview hyperlink?(Score: 46)

Created: 2014-02-14

If you want to change it programmatically:

yourText.setLinkTextColor(Color.RED);

See also original question in stackoverflow

#33: Android list view inside a scroll view (Score: 275)

Created: 2013-08-21 Last updated: 2017-07-27

Tags: android, android-layout, android-scrollview

I have an android layout which has a scrollView with a number of elements with in it. At the bottom of the scrollView I have a listView which is then populated by an adapter.

The problem that I am experiencing, is that android is excluding the listView from the scrollView as the scrollView already has a scroll-able function. I want the listView to be as long as the content is and for the master scroll view to be scroll-able.

How can I achieve this behavior?

Here is my main layout:

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="2"
    android:fillViewport="true"
    android:gravity="top" >

    <LinearLayout
        android:id="@+id/foodItemActvity_linearLayout_fragments"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>
    
</ScrollView>

I then programmatically add my components to the linearlayour with the id: foodItemActvity_linearLayout_fragments. Below is one of the views that is loaded into that linearlayout. This is the one giving me trouble with the scrolls.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
       android:id="@+id/fragment_dds_review_textView_label"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Reviews:"
       android:textAppearance="?android:attr/textAppearanceMedium" />

   <ListView
       android:id="@+id/fragment_dds_review_listView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
   </ListView>
</LinearLayout>

My adapter then fills up this list view.

Here is an image from the android hierarchy viewer when I click on the master scrollView:

Android List View inside a scroll view

As you can see, it is excluding the reviews listView.

I should be able to scroll the page down and see 8 reviews, but instead it only shows me those 3, and I can scroll on the tiny part where the reviews are. I want a global page scroll

#33 Best answer 1 of Android list view inside a scroll view (Score: 569)

Created: 2013-10-11 Last updated: 2020-12-01

The shortest & easiest solution for any ChildView to scroll inside a ScrollView. Anything like ListView, RecyclerView, etc. You do not have to do anything special in code.

Just replace ScrollView with androidx.core.widget.NestedScrollView in your current xml and then magic happens.

Below is a sample xml code :

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView
    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="match_parent">

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp"
        android:paddingBottom="20dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Recycler View inside a Scroll View"
            android:textColor="@color/black"
            android:textSize="@dimen/_20sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="Below is a Recycler View as an example."
            android:textSize="16sp" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@id/et_damaged_qty" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="This textview automatically goes below the Recycler View."
            android:textSize="16sp" />
    </androidx.appcompat.widget.LinearLayoutCompat>
</androidx.core.widget.NestedScrollView>

Now you can get rid of all the ugly hacks we did to get around this nested scrolling.

#33 Best answer 2 of Android list view inside a scroll view(Score: 223)

Created: 2013-12-09 Last updated: 2020-12-01

The answer is simple and I am surprised it has yet to be answered here.

Use a Header View or/and Footer View on the list itself. Don’t mix a ScrollView with a ListView or anything that can scroll. It’s meant to be used with headers and footers :)

Essentially, take all the content above your ListView, put it in another .xml file as a layout and then in code inflate it and add it to the list as a header view.

i.e.

View header = getLayoutInflater().inflate(R.layout.header, null);
View footer = getLayoutInflater().inflate(R.layout.footer, null);
listView.addHeaderView(header);
listView.addFooterView(footer);

See also original question in stackoverflow

#34: How to change the color of a CheckBox? (Score: 274)

Created: 2011-05-02 Last updated: 2020-02-17

Tags: android, android-layout, android-checkbox

How do I change the default CheckBox color in Android?
By default the CheckBox color is green, and I want to change this color.
If it is not possible please tell me how to make a custom CheckBox?

#34 Best answer 1 of How to change the color of a CheckBox? (Score: 395)

Created: 2015-11-20 Last updated: 2019-01-10

You can change the color directly in XML. Use buttonTint for the box: (as of API level 23)

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:buttonTint="@color/CHECK_COLOR" />

You can also do this using appCompatCheckbox v7 for older API levels:

<android.support.v7.widget.AppCompatCheckBox 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    app:buttonTint="@color/COLOR_HERE" /> 

#34 Best answer 2 of How to change the color of a CheckBox?(Score: 245)

Created: 2011-05-02 Last updated: 2019-03-23

If your minSdkVersion is 21+ use android:buttonTint attribute to update the color of a checkbox:

<CheckBox
  ...
  android:buttonTint="@color/tint_color" />

In projects that use AppCompat library and support Android versions below 21 you can use a compat version of the buttonTint attribute:

<CheckBox
  ...
  app:buttonTint="@color/tint_color" />

In this case if you want to subclass a CheckBox don’t forget to use AppCompatCheckBox instead.

PREVIOUS ANSWER:

You can change CheckBoxs drawable using android:button="@drawable/your_check_drawable" attribute.

See also original question in stackoverflow

#35: How to set layout_weight attribute dynamically from code? (Score: 272)

Created: 2011-01-09 Last updated: 2018-07-31

Tags: android, android-layout, android-layout-weight

How can I set the value for the attribute layout_weight for button in android dynamically from java code ?

#35 Best answer 1 of How to set layout_weight attribute dynamically from code? (Score: 505)

Created: 2011-01-09 Last updated: 2017-02-27

You can pass it in as part of the LinearLayout.LayoutParams constructor:

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
    LayoutParams.MATCH_PARENT,
    LayoutParams.MATCH_PARENT,
    1.0f
);
YOUR_VIEW.setLayoutParams(param);

The last parameter is the weight.

#35 Best answer 2 of How to set layout_weight attribute dynamically from code?(Score: 126)

Created: 2011-01-09 Last updated: 2014-02-24

Use LinearLayout.LayoutParams:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
Button button = new Button(this);
button.setLayoutParams(params);

EDIT: Ah, Erich’s answer is easier!

See also original question in stackoverflow

#36: Android: How to create a Dialog without a title? (Score: 271)

Created: 2010-04-15 Last updated: 2014-02-05

Tags: android, android-layout, dialog

I’m trying to generate a custom dialog in Android. I create my Dialog like this:

dialog = new Dialog(this);
dialog.setContentView(R.layout.my_dialog);

Everythings works fine except for the title of the Dialog. Even if I don’t set the title of the dialog the dialog popup has a blank space at the position of the dialog.

Is there any way to hide this part of the Dialog?

I tried it with an AlertDialog but it seems the layout is not set properly:

LayoutInflater inflater = 
    (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.map_dialog, null);

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(view);

// dialog = new Dialog(this);
// dialog.setContentView(R.layout.map_dialog);

dialog = builder.create();

((TextView) dialog.findViewById(R.id.nr)).setText(number);

If I use this code I get a null Pointer Exception in the last line. The dialog is not null so the TextView I try to retrieve does not exist.
If I uncomment the part where I use the Dialog Constructor everything works fine but for the title above my dialog layout.

#36 Best answer 1 of Android: How to create a Dialog without a title? (Score: 587)

Created: 2010-08-04

FEATURE_NO_TITLE works when creating a dialog from scratch, as in:

Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

But it doesn’t work when creating an AlertDialog (or using the Builder), because it already disables the title and use a custom one internally.

I have looked at the SDK sources, and I think that it can’t be worked around. So to remove the top spacing, the only solution is to create a custom dialog from scratch IMO, by using the Dialog class directly.

Also, one can do that with a style, eg in styles.xml:

<style name="FullHeightDialog" parent="android:style/Theme.Dialog">
   <item name="android:windowNoTitle">true</item>
</style>

And then:

Dialog dialog = new Dialog(context, R.style.FullHeightDialog);

#36 Best answer 2 of Android: How to create a Dialog without a title?(Score: 210)

Created: 2010-04-15 Last updated: 2015-07-31

You can hide the title of a dialog using:

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);


Previous version of this answer, which is overcomplicated:

You need to use an AlertDialog. There’s a good explanation on the Android Developer’s site about custom dialogs.

In very short summary, you do this with code like copied below from the official website. That takes a custom layot file, inflates it, gives it some basic text and icon, then creates it. You’d show it then with alertDialog.show().

AlertDialog.Builder builder;
AlertDialog alertDialog;

Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater)
        mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
        (ViewGroup) findViewById(R.id.layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);

builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();

In response to comment:

I assume that TextView with the id nr is in the View you are inflating with View view = inflater..... If so, then you need to change just one bit: instead of dialog.findView... make it view.findView.... Then once you’ve done that, remember to use dialog.show(), or even builder.show() without bothering to do builder.create().

See also original question in stackoverflow

#37: How to animate RecyclerView items when they appear (Score: 269)

Created: 2014-11-03 Last updated: 2018-12-29

Tags: android, android-layout, android-recyclerview

How can I animate the RecyclerView Items when there are appearing?

The default item animator only animates when a data is added or removed after the recycler data has been set. I’m new developing applications and don’t have any clue where to start.

Any ideas how to achieve this?

#37 Best answer 1 of How to animate RecyclerView items when they appear (Score: 327)

Created: 2014-11-05 Last updated: 2017-01-03

EDIT :

According to the ItemAnimator documentation :

This class defines the animations that take place on items as changes are made to the adapter.

So unless you add your items one by one to your RecyclerView and refresh the view at each iteration, I don’t think ItemAnimator is the solution to your need.

Here is how you can animate the RecyclerView items when they appear using a CustomAdapter :

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder>
{
    private Context context;
    
    // The items to display in your RecyclerView
    private ArrayList<String> items;
    // Allows to remember the last item shown on screen
    private int lastPosition = -1;

    public static class ViewHolder extends RecyclerView.ViewHolder
    {
        TextView text;
        // You need to retrieve the container (ie the root ViewGroup from your custom_item_layout)
        // It's the view that will be animated
        FrameLayout container;

        public ViewHolder(View itemView)
        {
            super(itemView);
            container = (FrameLayout) itemView.findViewById(R.id.item_layout_container);
            text = (TextView) itemView.findViewById(R.id.item_layout_text);
        }
    }

    public CustomAdapter(ArrayList<String> items, Context context)
    {
        this.items = items;
        this.context = context;
    }

    @Override
    public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_item_layout, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position)
    {
        holder.text.setText(items.get(position));
        
        // Here you apply the animation when the view is bound
        setAnimation(holder.itemView, position);
    }

    /**
     * Here is the key method to apply the animation
     */
    private void setAnimation(View viewToAnimate, int position)
    {
        // If the bound view wasn't previously displayed on screen, it's animated
        if (position > lastPosition)
        {
            Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
            viewToAnimate.startAnimation(animation);
            lastPosition = position;
        }
    }
}

And your custom_item_layout would look like this :

<FrameLayout
    android:id="@+id/item_layout_container"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/item_layout_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:gravity="center_vertical"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"/>

</FrameLayout>

For more information about CustomAdapters and RecyclerView, refer to this training on the official documentation.

Problems on fast scroll

Using this method could cause problems with fast scrolling. The view could be reused while the animation is been happening. In order to avoid that is recommendable to clear the animation when is detached.

    @Override
    public void onViewDetachedFromWindow(final RecyclerView.ViewHolder holder)
    {
        ((CustomViewHolder)holder).clearAnimation();
    }

On CustomViewHolder:

    public void clearAnimation()
    {
        mRootLayout.clearAnimation();
    }

Old answer :

Give a look at Gabriele Mariotti’s repo, I’m pretty sure you’ll find what you need. He provides simple ItemAnimators for the RecyclerView, such as SlideInItemAnimator or SlideScaleItemAnimator.

#37 Best answer 2 of How to animate RecyclerView items when they appear(Score: 85)

Created: 2019-02-13 Last updated: 2020-12-17

Made Simple with XML only

Visit Gist Link

res/anim/layout_animation.xml

<?xml version="1.0" encoding="utf-8"?>
    <layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:animation="@anim/item_animation_fall_down"
        android:animationOrder="normal"
        android:delay="15%" />

res/anim/item_animation_fall_down.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500">

    <translate
        android:fromYDelta="-20%"
        android:toYDelta="0"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

    <scale
        android:fromXScale="105%"
        android:fromYScale="105%"
        android:toXScale="100%"
        android:toYScale="100%"
        android:pivotX="50%"
        android:pivotY="50%"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

</set>

Use in layouts and recylcerview like:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layoutAnimation="@anim/layout_animation"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

See also original question in stackoverflow

#38: Android LinearLayout Gradient Background (Score: 268)

Created: 2011-05-12 Last updated: 2013-07-20

Tags: android, android-layout, android-linearlayout, gradient

I am having trouble applying a gradient background to a LinearLayout.

This should be relatively simple from what I have read but it just doesn’t seem to work. For reference sakes I am developing on 2.1-update1.

header_bg.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
	android:shape="rectangle">
	<gradient
        android:angle="90"
        android:startColor="#FFFF0000"
        android:endColor="#FF00FF00"
        android:type="linear"/>
</shape>

main_header.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
	android:layout_height="50dip"
	android:orientation="horizontal"
	android:background="@drawable/header_bg">
</LinearLayout>

If I change @drawable/header_bg to a color - e.g. #FF0000 it works perfectly fine. Am I missing something obvious here?

#38 Best answer 1 of Android LinearLayout Gradient Background (Score: 435)

Created: 2011-05-13

Ok I have managed to solve this using a selector. See code below:

main_header.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="50dip"
    android:orientation="horizontal"
    android:background="@drawable/main_header_selector">
</LinearLayout>

main_header_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
	<shape>
        <gradient
            android:angle="90"
            android:startColor="#FFFF0000"
            android:endColor="#FF00FF00"
            android:type="linear" />
	</shape>
</item>
</selector>

Hopefully this helps someone who has the same problem.

#38 Best answer 2 of Android LinearLayout Gradient Background(Score: 95)

Created: 2015-09-23 Last updated: 2017-10-26

It is also possible to have the third color (center). And different kinds of shapes.

For example in drawable/gradient.xml:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#000000"
        android:centerColor="#5b5b5b"
        android:endColor="#000000"
        android:angle="0" />
</shape>

This gives you black - gray - black (left to right) which is my favorite dark background atm.

Remember to add gradient.xml as background in your layout xml:

android:background="@drawable/gradient"

It is also possible to rotate, with:

angle=“0”

gives you a vertical line

and with

angle=“90”

gives you a horizontal line

Possible angles are:

0, 90, 180, 270.

Also there are few different kind of shapes:

android:shape=“rectangle”

Rounded shape:

android:shape=“oval”

and problably a few more.

Hope it helps, cheers!

See also original question in stackoverflow

#39: Add padding on view programmatically (Score: 258)

Created: 2012-03-13 Last updated: 2021-02-13

Tags: android, android-layout, android-emulator, android-widget, padding

I am developing Android v2.2 app.

I have a Fragment. In the onCreateView(...) callback of my fragment class, I inflate an layout to the fragment like below:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	View view = inflater.inflate(R.layout.login, null);
		
	return view;
}

The above inflated layout file is (login.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Username" />

    
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Username" />

</LinearLayout>

I would like to set a paddingTop to the above <LinearLayout> element , and I want to do it in the Java code instead of do it in xml.

How to set paddingTop to <LinearLayout> in my fragment Java class code ??

#39 Best answer 1 of Add padding on view programmatically (Score: 530)

Created: 2012-03-13 Last updated: 2013-10-11

view.setPadding(0,padding,0,0);

This will set the top padding to padding-pixels.

If you want to set it in dp instead, you can do a conversion:

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);

#39 Best answer 2 of Add padding on view programmatically(Score: 111)

Created: 2012-03-13 Last updated: 2018-02-10

To answer your second question:

view.setPadding(0,padding,0,0);

like SpK and Jave suggested, will set the padding in pixels. You can set it in dp by calculating the dp value as follows:

int paddingDp = 25;
float density = context.getResources().getDisplayMetrics().density
int paddingPixel = (int)(paddingDp * density);
view.setPadding(0,paddingPixel,0,0);

Hope that helps!

See also original question in stackoverflow

#40: Avoid passing null as the view root (need to resolve layout parameters on the inflated layout's root element) (Score: 248)

Created: 2014-07-18 Last updated: 2016-08-07

Tags: android, android-layout, warnings, layout-inflater

Passing null for root studio gives me this warning:

Avoid passing null as the view root (need to resolve layout parameters on the inflated layout’s root element)

It is showing a null value in getGroupView. Please help.

public class ExpandableListAdapter extends BaseExpandableListAdapter {

    private Context _context;
    private List<String> _listDataHeader; // header titles
    // child data in format of header title, child title
    private HashMap<String, List<String>> _listDataChild;

    public ExpandableListAdapter(Context context, List<String> listDataHeader,
                                 HashMap<String, List<String>> listChildData) {
        super();
        this._context = context;
        this._listDataHeader = listDataHeader;
        this._listDataChild = listChildData;
    }

    @Override
    public Object getChild(int groupPosition, int childPosititon) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .get(childPosititon);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(int groupPosition, final int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {

        final String childText = (String) getChild(groupPosition, childPosition);

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_item, null);


        }

        TextView txtListChild = (TextView) convertView
                .findViewById(R.id.lblListItem);

        txtListChild.setText(childText);
        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this._listDataHeader.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return this._listDataHeader.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        String headerTitle = (String) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_group, null);
        }

        TextView lblListHeader = (TextView) convertView
                .findViewById(R.id.lblListHeader);
        lblListHeader.setTypeface(null, Typeface.BOLD);
        lblListHeader.setText(headerTitle);

        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

}

#40 Best answer 1 of Avoid passing null as the view root (need to resolve layout parameters on the inflated layout's root element) (Score: 383)

Created: 2014-07-18

Instead of doing

convertView = infalInflater.inflate(R.layout.list_item, null);

do

convertView = infalInflater.inflate(R.layout.list_item, parent, false);

It will inflate it with the given parent, but won’t attach it to the parent.

#40 Best answer 2 of Avoid passing null as the view root (need to resolve layout parameters on the inflated layout's root element)(Score: 56)

Created: 2014-08-27 Last updated: 2020-10-20

I found a good article about LayoutInflater. The author explains how all the versions of the inflate method work and gives examples of ListView and AlertDialog

http://www.doubleencore.com/2013/05/layout-inflation-as-intended/

Update #1.

This answer recently helped me, too. https://stackoverflow.com/a/5027921/1065835

See also original question in stackoverflow


Notes:
  1. This page use API to get the relevant data from stackoverflow community.
  2. Content license on this page is CC BY-SA 3.0.
  3. score = up votes - down votes.