问题
If I have defined a Activity:
public class DialogActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(dialog_activity.xml);
}
}
I would like to display the above activity like a dialog, so in the AndroidManifest.xml file, I declare this activity like below:
<activity android:name=".DialogActivity" android:theme="@android:style/Theme.Dialog"/>
Everything is fine at this point, my DialogActivity
showed as a dialog.
The problem is How to customize the width and height of the DialogActivity
to make it more like a small dialog? (Currently it occupies most of the screen by default)
----------------------------Update-----------------------
I defined a custom theme like below:
<style name="myDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:width">100dip</item>
<item name="android:height">100dip</item>
</style>
Then, declare the DialogActivity
in AndroidManifest.xml as.
<activity android:name=".DialogActivity" android:theme="@style/myDialog"/>
My DialogActivity
now even occupies the whole screen:( . The width and height definition:
<item name="android:width">100dip</item>
in the theme do not take any effect, why?
回答1:
I finally figured out one way to customize the size of my DialogActivity
.
That's inside the onCreate()
method of DialogActivity
, add the following code:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.x = -20;
params.height = 100;
params.width = 550;
params.y = -10;
this.getWindow().setAttributes(params);
回答2:
You can just change params of window in your acctivity like:
override fun onStart() {
super.onStart()
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
回答3:
I had similar problem, I used following theme for my activity
android:theme="@style/Base.Theme.AppCompat.Light.Dialog"
The following code fixed my problem
setContentView(R.layout.activity_layout);
getWindow().setLayout(width(pixels),height(pixels));
回答4:
You can set the layout height and width in layout xml file
You can even mention the values like "240px" for android:layout_width/android:layout_height
回答5:
There's a one-line code without hassling with the LayoutParams that is
getWindow().setLayout((int)(width*.8),(int)(height*.25));
This is what I've used before in one of my projects and now searching for, but found it in the same project.
来源:https://stackoverflow.com/questions/6624480/how-to-customize-the-width-and-height-when-show-an-activity-as-a-dialog