I have a custom View
which I use for my AlertDialog
's title and content, here's the view:
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>
And I want AlertDialog
to wrap it's contents. I've been following solutions from this thread: AlertDialog with custom view: Resize to wrap the view's content but none of them works for me.
Solution 1, no effect at all, AlertDialog
takes the whole space:
// 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)
Solution 2 which uses forceWrapContent
to modify a view hierarchy, has an effect on content but the title is unaffected:
// 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();
}
Are there any other solutions or can I somehow modify the existing ones to make them work?