Android - Dialog Fragment width keeps on matching parent - android

Good day, apologies if this seems to be a duplicate of a question that's been asked before.
I have and Android App and I am displaying a Dialog Fragment. The problem I have is that the width of the Dialog Fragment is ignored when the base activity is showing it. Here's the code in my onCreateDialog function:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = new Dialog(getActivity());
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
LayoutInflater layoutInflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout2 = layoutInflater.inflate(R.layout.fragment_item_dialog, null);
dialog.setContentView(layout2);
setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialog);
Window window = dialog.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
window.setGravity(Gravity.TOP|Gravity.LEFT);
WindowManager.LayoutParams params = window.getAttributes();
params.x = 20;
params.y = 470;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.copyFrom(window.getAttributes());
window.setAttributes(params);
// -- more code here
}
and here is my xml file fragment_item_dialog
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="400dp"
android:layout_height="wrap_content" >
<!--- code here ---!>
</RelativeLayout>
The height is followed properly, but Android keeps on setting the width to match parent even though I told it to wrap content. The components inside my dialog Fragment does not exceed 400dp and I have no clue why Android is forcing my layout to match parent.
Does anyone know how to work around this? Any help is very much appreciated. Thanks.

Made it work, use the same code on onStart()
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (getDialog() == null)
return;
int width = 1100;
int height = getResources().getDisplayMetrics().heightPixels;
getDialog().getWindow().setLayout(width,
WindowManager.LayoutParams.WRAP_CONTENT);
}

Related

Full width Dialog, placed just above the soft keyboard

I want to achieve the following design: A dialog with custom layout, created programatically. It will contain an EditText and a Button. I want the soft keyboard to pop up when the dialog appears, and I want the dialog to fill the screen horizontally and to be placed right above the keyboard.
Here is what I've done right now:
final AlertDialog obsDialog = new AlertDialog.Builder(ProdutoDetalheActivity.this).create();
final View obsLayout = View.inflate(getApplicationContext(), R.layout.observation_layout, null);
Button obsButton = (Button) obsLayout.findViewById(R.id.observation_button);
obsEdit = (EditText) obsLayout.findViewById(R.id.observation_edit);
obsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text.setText(String.valueOf(obsEdit.getText()));
obsDialog.dismiss();
}
});
obsDialog.setView(obsLayout);
obsDialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
obsDialog.show();
obsEdit.requestFocus();
But this doesn't makes the dialog full width, nor calls the soft keyboard. And I still wonder how can I align the dialog with the keyboard.
I've tried these answers with no success.
Thanks in advance for any help!
[EDIT] I've brought the keyboard up by using the following code:
obsDialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
obsDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
[EDIT] Below is a printscreen of the design I want to achieve:
As far as I know, you have to adjust the dialog size/position in the code if you do not want the default size/position.
In you case specifically, you can fist declare adjustResize for the activity's windowSoftInputMode in the AndroidManifest.xml.
After that, you can set your dialog gravity at bottom and set the width in the onStart of the dialog fragment:
...
getDialog().getWindow().setLayout(mWidth, mHeight);
WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
lp.gravity = Gravity.BOTTOM;
lp.x = 0; lp.y = 0;
getDialog().getWindow().setAttributes(lp);
...
the mWidth and mHeight are initialized in onCreate, but I think you can do it in the onStart as well. To get the width, I used below code:
Point size = new Point();
WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getSize(size);
mWidth = size.x;
Hope this can meet your requirement. I used this to create a similar dialog, but I do not have a edit in the dialog. And I need it to be at the bottom of the screen.

Android custom AlertDialog changed width not accurate

I have a DialogFragment where I create the alertDialog in the onCreate():
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
if (alertDialog == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
alertDialog = builder.create();
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
alertDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
}
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.setView(getDialogLayout(),0,0,0,0);
return alertDialog;
}
Then I set the width (dialogWidth) of alertDialog in the onStart():
#Override
public void onStart() {
super.onStart();
WindowManager.LayoutParams lp = alertDialog.getWindow().getAttributes();
lp.width = dialogWidth;
lp.x = Constants.iX_PositionDialog;
lp.y = Constants.iY_PositionDialog;
alertDialog.getWindow().setAttributes(lp);
}
In my case i set the width of the dialog to 648 but the canvas/window of my surfaceView is just 590, why?
I need the width i set.
Set the layout after show() method of alertDialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Title");
alertDialog = builder.create();
alertDialog.show();
alertDialog.getWindow().setLayout(648, 400); //Controlling width and height.
NOTE: Setting the layout after show() is the key point.
For more - how-to-control-the-width-and-height-of-default-alert-dialog-in-android.
To set the width and height of your alert dialouge for siffrent screen use:
int dialogWidth = getActivity().getResources().getDisplayMetrics().widthPixels-120; // screen width - whatever the width you want to set.
int dialogHeight = getActivity().getResources().getDisplayMetrics().heightPixels -140; //screen height - whatever the width you want to set.
getDialog().setCanceledOnTouchOutside(false);
Window window = getDialog().getWindow();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.gravity = Gravity.CENTER;
lp.height = dialogHeight;
lp.width = dialogWidth;
window.setAttributes(lp);
its a best practice as in andorid there are many devices and of many resolution,so we have to do everythign according to diffrent screen.so that it will be feasible with all types of screens.
I found the solution for my self.
So the alertDialog View is packed in an few FrameLayouts.
the Padding of some of these are not 0.
According of this helping code here :[AlertDialog with custom view: Resize to wrap the view's content
I make it with the following methode which i call in the onStart methode:
protected void forceWrapContent(View v) {
// Start with the provided view
View current = v;
// Travel up the tree until fail, modifying the LayoutParams
do {
// Get the parent
ViewParent parent = current.getParent();
// Check if the parent exists
if (parent != null) {
// Get the view
try {
current = (View) parent;
} catch (ClassCastException e) {
// This will happen when at the top view, it cannot be cast to a View
break;
}
// Modify the layout
current.getLayoutParams().width = dialogWidth;
current.setPadding(0, 0, 0, 0);
}
} while (current.getParent() != null);
// Request a layout to be re-done
current.requestLayout();
}
Thanks!

Setting the size of a DialogFragment

I have been trying many commands to setup the size of my DialogFragment. It only contains a color-picker, so I have removed the background and title of the dialog:
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
However I also want to position the dialog where I want and it is problematic. I use:
WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
params.width = LayoutParams.WRAP_CONTENT;
params.height = LayoutParams.WRAP_CONTENT;
params.gravity = Gravity.LEFT;
getDialog().getWindow().setAttributes(params);
But one (big) obstacle remains: even though my dialog pane is invisible, it still has a certain size, and it limits the positions of my dialog. The LayoutParams.WRAP_CONTENT are here to limit the size of this pane to my color-picker, but for some reason it does not work.
Has anyone been able to do something similar?
i met a similar question that is you can't set the dialogFragment's width an height in code,after several try ,i found a solution;
here is steps to custom DialogFragment:
1.inflate custom view from xml on method
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().setCanceledOnTouchOutside(true);
View view = inflater.inflate(R.layout.XXX,
container, false);
//TODO:findViewById, etc
return view;
}
2.set your dialog's width an height in onResume(),remrember in onResume()/onStart(),seems didn't work in other method
public void onResume()
{
super.onResume();
Window window = getDialog().getWindow();
window.setLayout(width, height);
window.setGravity(Gravity.CENTER);
//TODO:
}
After some trial and error, I have found the solution.
here is the implementation of my DialogFragment class :
public class ColorDialogFragment extends SherlockDialogFragment {
public ColorDialogFragment() {
//You need to provide a default constructor
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_color_picker, container);
// R.layout.dialog_color_picker is the custom layout of my dialog
WindowManager.LayoutParams wmlp = getDialog().getWindow().getAttributes();
wmlp.gravity = Gravity.LEFT;
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.colorPickerStyle);
// this setStyle is VERY important.
// STYLE_NO_FRAME means that I will provide my own layout and style for the whole dialog
// so for example the size of the default dialog will not get in my way
// the style extends the default one. see bellow.
}
}
R.style.colorPickerStyle corresponds to :
<style name="colorPickerStyle" parent="Theme.Sherlock.Light.Dialog">
<item name="android:backgroundDimEnabled">false</item>
<item name="android:cacheColorHint">#android:color/transparent</item>
<item name="android:windowBackground">#android:color/transparent</item>
</style>
I simply extend a default Dialog style with my needs.
Finally, you can invoke this dialog with :
private void showDialog() {
ColorDialogFragment newFragment = new ColorDialogFragment();
newFragment.show(getSupportFragmentManager(), "colorPicker");
}
For my use case, I wanted the DialogFragment to match the size of a list of items. The fragment view is a RecyclerView in a layout called fragment_sound_picker. I added a wrapper RelativeLayout around the RecyclerView.
I had already set the individual list item view's height with R.attr.listItemPreferredHeight, in a layout called item_sound_choice.
The DialogFragment obtains a LayoutParams instance from the inflated View's RecyclerView, tweaks the LayoutParams height to a multiple of the list length, and applies the modified LayoutParams to the inflated parent View.
The result is that the DialogFragment perfectly wraps the short list of choices. It includes the window title and Cancel/OK buttons.
Here's the setup in the DialogFragment:
// SoundPicker.java
// extends DialogFragment
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getActivity().getString(R.string.txt_sound_picker_dialog_title));
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.fragment_sound_picker, null);
RecyclerView rv = (RecyclerView) view.findViewById(R.id.rv_sound_list);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
SoundPickerAdapter soundPickerAdapter = new SoundPickerAdapter(getActivity().getApplicationContext(), this, selectedSound);
List<SoundItem> items = getArguments().getParcelableArrayList(SOUND_ITEMS);
soundPickerAdapter.setSoundItems(items);
soundPickerAdapter.setRecyclerView(rv);
rv.setAdapter(soundPickerAdapter);
// Here's the LayoutParams setup
ViewGroup.LayoutParams layoutParams = rv.getLayoutParams();
layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = getListItemHeight() * (items.size() + 1);
view.setLayoutParams(layoutParams);
builder.setView(view);
builder.setCancelable(true);
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
// ...
});
builder.setPositiveButton(R.string.txt_ok, new DialogInterface.OnClickListener() {
// ...
});
return builder.create();
}
#Override
public void onResume() {
Window window = getDialog().getWindow();
window.setLayout(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
super.onResume();
}
private int getListItemHeight() {
TypedValue typedValue = new TypedValue();
getActivity().getTheme().resolveAttribute(R.attr.listPreferredItemHeight, typedValue, true);
DisplayMetrics metrics = new android.util.DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
return (int) typedValue.getDimension(metrics);
}
Here is fragment_sound_picker:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_sound_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
use this code for resize of Dialog Fragment android
public void onResume() {
super.onResume();
Window window = getDialog().getWindow();
window.setLayout(250, 100);
window.setGravity(Gravity.RIGHT);
}

how to set margin in Dialog

I have used Dialog for display ad in my Andorid app.But I have to display this Dialog about 50dp top from buttom so i think we should set Dialog Gravity buttom and set its buttom margine 50dp.But i'm unable to use margin in Dialog.so please can suggest me how to solve this.
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup_element"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/dialogback"
android:orientation="vertical" >
<WebView
android:id="#+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Java:
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
LayoutInflater inflator = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflator.inflate(R.layout.ad, null, false);
dialog.setContentView(view);
dialog.getWindow().setGravity(Gravity.BOTTOM);
dialog.setCancelable(true);
WebView webView = (WebView) dialog.findViewById(R.id.webView);
webView.loadUrl("");
webView.setWebViewClient(new MyWebViewClient());
webView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
I did a similar smiley dialog. I extend dialog
public class SmileCustomDialog extends Dialog {
Context mcontext;
GridView mGridview;
public GridView getGridview() {
return mGridview;
}
public SmileCustomDialog(final Context context) {
super(context, R.style.SlideFromBottomDialog);
this.mcontext = context;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.emocategorydialog, null);
mGridview = (GridView) v.findViewById(R.id.emogrid);
mGridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
ImageAdapter mAdapter = new ImageAdapter(mcontext);
mGridview.setAdapter(mAdapter);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(v);
WindowManager.LayoutParams params = this.getWindow().getAttributes();
this.setCanceledOnTouchOutside(true);
params.y = -100;
this.getWindow().setAttributes(params);
}
}
But the essential is
WindowManager.LayoutParams params = yourDialog.getWindow().getAttributes(); // change this to your dialog.
params.y = -100; // Here is the param to set your dialog position. Same with params.x
yourDialog.getWindow().setAttributes(params);
Just add this before your show your dialog.
WindowManager.LayoutParams:
public int x: X position... When using LEFT or START or RIGHT or END it provides an offset from the given edge
public int y: Y position... When using TOP or BOTTOM it provides an offset from the given edge
(http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#x)
thus:final Dialog dialog = new Dialog(context);
// ...
// e.g. top + right margins:
dialog.getWindow().setGravity(Gravity.TOP|Gravity.RIGHT);
WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
layoutParams.x = 100; // right margin
layoutParams.y = 170; // top margin
dialog.getWindow().setAttributes(layoutParams);
// e.g. bottom + left margins:
dialog.getWindow().setGravity(Gravity.BOTTOM|Gravity.LEFT);
WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
layoutParams.x = 100; // left margin
layoutParams.y = 170; // bottom margin
dialog.getWindow().setAttributes(layoutParams);
// etc.
You can create a style for your dialog and put margins there.
For example:
<style name="custom_style_dialog">
<item name="android:layout_marginStart">16dp</item>
<item name="android:layout_marginEnd">16dp</item>
</style>
Then, in your dialog class:
class CountryDialog(
context: Context
) : Dialog(context, R.style.custom_style_dialog) {
//your code here
}
This is an approach to set all four margins without having to care about gravity.
I tested my approach for a DialogFragment by applying it in the onCreateDialog method:
public Dialog onCreateDialog( Bundle savedInstanceState )
{
// create dialog in an arbitrary way
Dialog dialog = super.onCreateDialog( savedInstanceState );
DialogUtils.setMargins( dialog, 0, 150, 50, 75 );
return dialog;
}
This is the method applying the margins to the dialog:
public static Dialog setMargins( Dialog dialog, int marginLeft, int marginTop, int marginRight, int marginBottom )
{
Window window = dialog.getWindow();
if ( window == null )
{
// dialog window is not available, cannot apply margins
return dialog;
}
Context context = dialog.getContext();
// set dialog to fullscreen
RelativeLayout root = new RelativeLayout( context );
root.setLayoutParams( new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) );
dialog.requestWindowFeature( Window.FEATURE_NO_TITLE );
dialog.setContentView( root );
// set background to get rid of additional margins
window.setBackgroundDrawable( new ColorDrawable( Color.WHITE ) );
// apply left and top margin directly
window.setGravity( Gravity.LEFT | Gravity.TOP );
LayoutParams attributes = window.getAttributes();
attributes.x = marginLeft;
attributes.y = marginTop;
window.setAttributes( attributes );
// set right and bottom margin implicitly by calculating width and height of dialog
Point displaySize = getDisplayDimensions( context );
int width = displaySize.x - marginLeft - marginRight;
int height = displaySize.y - marginTop - marginBottom;
window.setLayout( width, height );
return dialog;
}
Here are the helper methods I used:
#NonNull
public static Point getDisplayDimensions( Context context )
{
WindowManager wm = ( WindowManager ) context.getSystemService( Context.WINDOW_SERVICE );
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics( metrics );
int screenWidth = metrics.widthPixels;
int screenHeight = metrics.heightPixels;
// find out if status bar has already been subtracted from screenHeight
display.getRealMetrics( metrics );
int physicalHeight = metrics.heightPixels;
int statusBarHeight = getStatusBarHeight( context );
int navigationBarHeight = getNavigationBarHeight( context );
int heightDelta = physicalHeight - screenHeight;
if ( heightDelta == 0 || heightDelta == navigationBarHeight )
{
screenHeight -= statusBarHeight;
}
return new Point( screenWidth, screenHeight );
}
public static int getStatusBarHeight( Context context )
{
Resources resources = context.getResources();
int resourceId = resources.getIdentifier( "status_bar_height", "dimen", "android" );
return ( resourceId > 0 ) ? resources.getDimensionPixelSize( resourceId ) : 0;
}
public static int getNavigationBarHeight( Context context )
{
Resources resources = context.getResources();
int resourceId = resources.getIdentifier( "navigation_bar_height", "dimen", "android" );
return ( resourceId > 0 ) ? resources.getDimensionPixelSize( resourceId ) : 0;
}
The helper methods are explained in another of my SO answers.
This Gist contains an extended versions that supports immersve mode too.
View view = layoutInflater.inflate(R.layout.dialog_layout, null);
AlertDialog infoDialog = new AlertDialog.Builder(this)
.setView(view)
.create();
Window window =infoDialog.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND );
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.dimAmount=(float) 0.0;
//wlp.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND ;
window.setAttributes(wlp);
infoDialog.show();
Change gravity to bottom
Well, what best worked for me was to wrap my dialog view inside a FrameLayout and add padding, and set onClickListener to "dismiss" dialog. Like this:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/parentFl"
android:background="#android:color/transparent"
android:padding="#dimen/vvlarge_margin">
dialog?.window?.setBackgroundDrawable(context?.getDrawable(android.R.color.transparent))
view.parentFl.setOnClickListener { dismiss() }
Another approach is to use the InsetDrawable. You simply specify the insetLeft & insetRight and apply it as your background like below:
inset_drawable.xml (Created in the drawable folder)
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="#drawable/dialog_bg" <!-- this is simply a shape drawable with corners applied-->
android:insetLeft="30dp" <!-- specify your dimension -->
android:insetRight="30dp" />
your_layout.xml (Your custom dialog)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup_element"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/inset_drawable"
android:orientation="vertical" >
<WebView
android:id="#+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

Brightness Screen Filter

Does anyone have an idea how to implement an Brightness Screen Filter like the one here:
http://www.appbrain.com/app/screen-filter/com.haxor
I need a starting point and I can't figure out how to do it.
Just make a transparent full screen activity that lets touches pass through. To make touches pass through use the following Window flags before setting the contentView:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Window window = getWindow();
// Let touches go through to apps/activities underneath.
window.addFlags(FLAG_NOT_TOUCHABLE);
// Now set up content view
setContentView(R.layout.main);
}
For your main.xml layout file just use a full screen LinearLayout with a transparent background:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/background"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#33000000">
</LinearLayout>
Then to adjust the "brightness" just change the value of the background colour from your code somewhere:
findViewById(R.id.background).setBackgroundColor(0x66000000);
Get an instance of WindowManager.
WindowManager windowManager = (WindowManager) Class.forName("android.view.WindowManagerImpl").getMethod("getDefault", new Class[0]).invoke(null, new Object[0]);
Create a full screen layout xml(layout parameters set to fill_parent)
Set your view as not clickable, not focusable, not long clickable, etc so that touch is passed through to your app and the app can detect it.
view.setFocusable(false);
view.setClickable(false);
view.setKeepScreenOn(false);
view.setLongClickable(false);
view.setFocusableInTouchMode(false);
Create a layout parameter of type android.view.WindowManager.LayoutParams.
LayoutParams layoutParams = new LayoutParams();
Set layout parameter like height, width etc
layoutParams.height = LayoutParams.FILL_PARENT;
layoutParams.width = LayoutParams.FILL_PARENT;
layoutParams.flags = 280; // You can try LayoutParams.FLAG_FULLSCREEN too
layoutParams.format = PixelFormat.TRANSLUCENT; // You can try different formats
layoutParams.windowAnimations = android.R.style.Animation_Toast; // You can use only animations that the system to can access
layoutParams.type = LayoutParams.TYPE_SYSTEM_OVERLAY;
layoutParams.gravity = Gravity.BOTTOM;
layoutParams.x = 0;
layoutParams.y = 0;
layoutParams.verticalWeight = 1.0F;
layoutParams.horizontalWeight = 1.0F;
layoutParams.verticalMargin = 0.0F;
layoutParams.horizontalMargin = 0.0F;
Key step: You can set what percentage of brightness you need.
layoutParams.setBackgroundDrawable(getBackgroundDrawable(i));
private Drawable getBackgroundDrawable(int i) {
int j = 255 - (int) Math.round(255D * Math.exp(4D * ((double) i / 100D) - 4D));
return new ColorDrawable(Color.argb(j, 0, 0, 0));}
Finally add view to windowManager that you created earlier.
windowManager.addView(view, layoutParams);
Note: You need SYSTEM_ALERT_WINDOW permission to lay an overlay on the screen.
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Have tested this and it works. Let me know if you get stuck.
Of course you can't use this is production code, but if you are playing around .. try this Undocumented hack
It uses :
private void setBrightness(int brightness) {
try {
IHardwareService hardware = IHardwareService.Stub.asInterface(
ServiceManager.getService("hardware"));
if (hardware != null) {
hardware.setScreenBacklight(brightness);
}
} catch (RemoteException doe) {
}
}
Remember that it uses this permission :
<uses-permission android:name="android.permission.HARDWARE_TEST"/>
You ca try this also:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.max_bright);
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 100 / 100.0f;
getWindow().setAttributes(lp);
}

Categories

Resources