Last active
April 4, 2016 12:14
-
-
Save Palatis/2f4e79daf2cfe088fa55adfd626966a4 to your computer and use it in GitHub Desktop.
Activities with Dialog theme doesn't always respect to LayoutParams. This class addresses this, so wrap_conetnt actually **does** wrap_content.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.support.v7.app.AppCompatActivity; | |
//import android.app.Activity; // import this if you don't want to use the AppComat package. | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.view.ViewParent; | |
import android.view.Window; | |
import android.view.WindowManager; | |
/** | |
* the activity with a Dialog theme doesn't really respect the "wrap_content" params. | |
* so we fix it here... | |
* <p/> | |
* Created by Palatis on 2016/4/4. | |
*/ | |
public abstract class RespectLayoutParamsActivity extends AppCompatActivity { | |
// extends android.app.Activity if you don't want the AppCompat package | |
//public abstract class RespectLayoutParamsActivity extends Activity { | |
/** | |
* get the root view of the view hierarchy. | |
* subclass should implement this to return the **real** root view, or it might make the window | |
* look weird. | |
* | |
* @return the root view | |
*/ | |
protected abstract View getRootView(); | |
private boolean mPayRespect = false; | |
@Override | |
protected void onStart() { | |
super.onStart(); | |
// force "fit-to-size", this should be done after super.onStart() | |
if (mPayRespect) | |
forceLayoutParams(); | |
} | |
private void forceLayoutParams() { | |
mPayRespect = false; | |
View view = getRootView(); | |
ViewGroup.LayoutParams rlp = view.getLayoutParams(); | |
final int widthParam = rlp.width; | |
final int heightParam = rlp.height; | |
final Window window = getWindow(); | |
window.setLayout(widthParam, heightParam); | |
final WindowManager.LayoutParams wlp = window.getAttributes(); | |
wlp.width = widthParam; | |
wlp.height = heightParam; | |
window.setAttributes(wlp); // we have to call this, else the window won't resize. | |
// Travel up the tree until fail, modifying the LayoutParams | |
do { | |
final ViewParent parent = view.getParent(); | |
if (parent != null) { | |
// Get the view | |
try { | |
view = (View) parent; | |
} catch (ClassCastException e) { | |
// This will happen when at the top view, it cannot be cast to a View | |
break; | |
} | |
// Modify the layout | |
final ViewGroup.LayoutParams lp = view.getLayoutParams(); | |
if (lp != null) { | |
lp.width = widthParam; | |
lp.height = heightParam; | |
} | |
} | |
} while (view.getParent() != null); | |
// Request a layout to be re-done | |
view.requestLayout(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment