我正在重复我在谷歌群组中的android群组中发表的帖子(http://groups.google.com/group/android-developers/browse_thread/thread/78d0b7496a51e3b7#),希望我能祝你好运!
我有一个显示项目列表的活动。单击某个项目后, 我显示一个带有一些按钮和图像的全屏对话框。这 横向看起来不错,但纵向看起来不太好(由于 图像长宽比)。我想知道是否有可能 无论当前屏幕如何,始终横向显示此对话框 方向。对话结束后,我将移交 方向回到传感器。这是我到目前为止所拥有的:
OnItemClickListener listlistener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View arg1, int position,
long arg3) {
final Dialog dialog = new Dialog(getParent());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
final int orientation =
getResources().getConfiguration().orientation;
if (orientation == 1){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
dialog.setContentView(R.layout.dialog);
dialog.setCancelable(true);
ImageView img = (ImageView) dialog.findViewById(R.id.img); //A
static image for testing UI
//BUTTON LISTENERS HERE
dialog.show();
dialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
});
}
};
但是这样做,屏幕会先改变方向,然后再尝试 显示对话框。但是在方向改变时屏幕是 重新启动活动,但我的对话框未显示。有没有更简单的 方法来做到这一点?我可以为对话框使用两种不同的布局吗 根据方向加载相应的?如果是这样,那么 纵向模式的 XML 是什么样子的? 谢谢!
如果您为对话框使用自定义布局,只需设计一个新的布局并将其放入layout-land文件夹中(如果需要的话创建它),这样它就会自动加载相应的布局。
您还可以旋转视图。那么你就不需要改变活动方向,这可能会导致一些其他问题。
如果您的屏幕有背景,那么您可以将背景添加到顶部视图组,然后将旋转添加到子视图组。因为旋转也适用于背景。
例如:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/rectangle_blue_24dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:rotation="90"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent">
<!-- Your views-->
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>