Ad

How Can We Get Width And Height In Non Activity Class And Non Fragment Class

- 1 answer

I have an alert dialog and i want to set width and height to it depend on my screen device and not constant like 1300,880.

How can i get width and height in non activity and non fragment class?

static abstract class BaseHolder extends RecyclerView.ViewHolder {
.
.
.

   LayoutInflater inflater = (LayoutInflater) mViewAction.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mDialog = new Dialog(mViewAction.getContext());    
        mDialogView = inflater.inflate(R.layout.dialog_deletetoken, null);
        mDialog.setContentView(mDialogView);


mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    mDialog.getWindow().setLayout(1300,880);
}
Ad

Answer

You can't directly get your value of height width of component, which are fully dependent on activity lifecycle.

What you can do, you can pass e reference to the context available in a non activity class and get results via that context.

Say for example, you want to get device screen ratio or height/width or density, you can do something like this:

public static int getScreenHeightInDP(Context context) {
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();

    float screenHeightInDP = displayMetrics.heightPixels / displayMetrics.density;

    return Math.round(screenHeightInDP);
}

Edit

for your case, make a Utility class like this,

public class Utility {


public static void setLayout(DialogFragment dialogFragment) {
    DisplayMetrics displayMetrics = dialogFragment.getResources().getDisplayMetrics();

    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels;

    if(dialogFragment.getDialog().getWindow()!=null)
        dialogFragment.getDialog().getWindow().setLayout(width,height);

}
}
Ad
source: stackoverflow.com
Ad