web-dev-qa-db-fra.com

comment définir la marge dans le dialogue

J'ai utilisé Dialog pour la publicité graphique dans mon application Andorid.Mais je dois afficher cette Dialog d'environ 50dp en haut de la cible, donc je pense que nous devrions définir la variable Dialog Gravity et sa marge de 50dp.Mais je suis incapable d'utiliser la marge dans Dialog .so s'il vous plaît pouvez me suggérer comment résoudre ce problème.

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();
11
Dilip

J'ai fait un dialogue similaire smiley. J'étend le dialogue 

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);

}

}

Mais l'essentiel c'est 

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);

Il suffit d’ajouter ceci avant de montrer votre dialogue.

19
Nam Trung

WindowManager.LayoutParams:
public int x: position X ... En utilisant LEFT ou START ou RIGHT ou END, il fournit un décalage par rapport au bord donné
public int y: position Y ... Lorsque vous utilisez TOP ou BOTTOM, il fournit un décalage par rapport au bord donné.
( http://developer.Android.com/reference/Android/view/WindowManager.LayoutParams.html#x )
Ainsi:

dialogue final de dialogue = nouveau dialogue (contexte); 
 // ... 
 // ex. Marges en haut et à droite: 
 dialog.getWindow (). setGravity (Gravity.TOP | Gravity.RIGHT); 
 WindowManager.LayoutParams layoutParams = dialog.getWindow (). getAttributes (); 
 layoutParams.x = 100; // marge droite 
 layoutParams.y = 170; // marge supérieure 
 dialog.getWindow (). setAttributes (layoutParams); 
 // p. ex. marges inférieure + gauche: 
 dialog.getWindow (). setGravity (Gravity.BOTTOM | Gravity.LEFT); 
 WindowManager.LayoutParams layoutParams = dialog.getWindow (). getAttributes (); 
 layoutParams.x = 100; // marge de gauche 
 layoutParams.y = 170; // marge inférieure 
 dialog.getWindow (). setAttributes (layoutParams); 
 
 // etc.
15
Sergey Burish
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();

Changer la gravité vers le bas 

3
Jaiprakash Soni

Cette approche permet de définir les quatre marges sans se soucier de la gravité.

J'ai testé mon approche pour une DialogFragment en l'appliquant dans la méthode onCreateDialog:

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;
}

C'est la méthode qui applique les marges à la boîte de dialogue:

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;
}

Voici les méthodes d'assistance que j'ai utilisées:

@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;
}

Les méthodes auxiliaires sont expliquées dans une autre de mes SO réponses

This Gist contient une version étendue qui prend également en charge le mode immersion.

1
Peter F