【发布时间】:2015-12-06 13:48:21
【问题描述】:
我有一个自定义的View 用于我的AlertDialog 的标题和内容,这是视图:
view_tip.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" style="@style/StandardLinearLayout"
android:layout_height="match_parent" android:layout_width="match_parent">
<TextView
android:maxWidth="245sp"
android:id="@+id/actionTip"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
我希望AlertDialog 包装它的内容。我一直在关注这个帖子的解决方案:AlertDialog with custom view: Resize to wrap the view's content 但它们都不适合我。
方案一,完全没有效果,AlertDialog 占满整个空间:
// Scala code
val title = getLayoutInflater.inflate(R.layout.view_tip, null)
title.findViewById(R.id.actionTip).asInstanceOf[TextView] setText "title"
val view = getLayoutInflater.inflate(R.layout.view_tip, null)
view.findViewById(R.id.actionTip).asInstanceOf[TextView] setText "content"
val dialog = new android.app.AlertDialog.Builder(this).setCustomTitle(title).setView(view).show
dialog.getWindow.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
解决方案 2 使用 forceWrapContent 修改视图层次结构,对内容有影响但标题不受影响:
// Scala code
val title = getLayoutInflater.inflate(R.layout.view_tip, null)
title.findViewById(R.id.actionTip).asInstanceOf[TextView] setText "title"
val view = getLayoutInflater.inflate(R.layout.view_tip, null)
view.findViewById(R.id.actionTip).asInstanceOf[TextView] setText "content"
val dialog = new android.app.AlertDialog.Builder(this).setCustomTitle(title).setView(view).show
forceWrapContent(title)
forceWrapContent(view)
...
// Java code
static 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 = ViewGroup.LayoutParams.WRAP_CONTENT;
}
} while (current.getParent() != null);
// Request a layout to be re-done
current.requestLayout();
}
是否有任何其他解决方案,或者我可以以某种方式修改现有的解决方案以使其正常工作?
【问题讨论】:
标签: android layout android-alertdialog