对话框中的列表项宽度与父容器不匹配

6

我正在尝试在对话框中创建一个仅包含字符串对象的简单 listView;问题是列表项没有设置为 match_parent

enter image description here

列表视图是根元素:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ff0000"
    android:id="@+id/lvLinks"
    android:layout_height="match_parent"/ >

列表项:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:padding="7dp"
    android:textSize="15sp"
    android:background="#0000ff"
    android:layout_height="match_parent" />

适配器:

ListView lv = (ListView) findViewById(R.id.lvLinks);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,R.layout.list_item_links,items);
lv.setAdapter(adapter);

我已在许多操作系统上进行了测试,这不是问题所在。

修复: 答案

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ListView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:background="#ff0000"
        android:id="@+id/lvLinks"
        android:layout_height="match_parent" />
</LinearLayout>

请提供有关如何创建对话框的相关代码。它是DialogFragment吗? - Lamorak
我认为TextView的主布局是wrap_content,因此它没有占满整个宽度,请检查一下。 - Hanuman
我在使用DialogFragment时遇到了同样的问题,建议的答案并没有起作用。 - Waza_Be
3个回答

10
为什么不将你的ListView放在宽度为match_parent或fill_parent的LinearLayout或RelativeLayout中 dialog.xml

是的 @itzhar,但你还需要一些主要布局,你可以查看它可能会对你有所帮助。将其方向设置为垂直,并将宽度设置为“match_parent”。 - ULHAS PATIL
这个也不行,有时候项目仍然没有被拉伸。经典的谷歌,太多的漏洞了... - qkx
@qkx 请添加您的代码。这样我们也能解决它。 - ULHAS PATIL
在活动中这不是问题,但在具有自定义布局的对话框中,由于Android源代码中存在错误,它无法正常工作。你可以试一下 :) 它不能在XML中修复(只能通过代码解决),关于此类问题在stackoverflow上有很多类似的主题。很抱歉,我在第一次回答中应该更加精确地说明,在对话框中它无法正常工作。 - qkx

0

对我来说,提出的方案并没有解决我的问题。实际上,这个问题只在小米MIUI设备上显示出来,在Google原版、三星或一加设备上没有出现过。

相反,我将以下代码添加到我的自定义listView构造函数中:

    addOnLayoutChangeListener(this);

还有监听器:

@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom)
{
    int I = getChildCount();
    for(int i = 0; i < I; i++)
    {
        getChildAt(i).requestLayout();
    }
}

0

这可能不是精确的解决方案,但您可以尝试以下 XML 代码来处理列表项

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
<TextView 
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:padding="7dp"
    android:textSize="15sp"
    android:background="#0000ff"
    android:layout_height="wrap_content" /> 
</LinearLayout>

不需要创建自定义适配器,因为它具有Android TextView默认ID android:id="@android:id/text1"。您可以使用ArrayAdapter与此布局。 - Amit Padekar
2
该布局甚至无法打开对话框。 - itzhar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接