[android] How to set layout_gravity programmatically?

The rest of the answers are right, I want to add more explaination. The layout_gravity is about how to position the view in parent view.

You must set gravity **after method parentView.addView() ** was called. We can see the code:

public void setLayoutParams(ViewGroup.LayoutParams params) {
    if (params == null) {
        throw new NullPointerException("Layout parameters cannot be null");
    }
    mLayoutParams = params;
    resolveLayoutParams();
    if (mParent instanceof ViewGroup) {
        ((ViewGroup) mParent).onSetLayoutParams(this, params);
    }
    requestLayout();
}

And the problem of null pointer is because it's not calling addView before getLayoutParams().

The annotation was already said "This method may return null if this View is not attached to a parent ViewGroup or {@link#setLayoutParams(android.view.ViewGroup.LayoutParams)} was not invoked successfully. When a View is attached to a parent ViewGroup, this method must not return null."