Android 将内容视图添加到对话框中

Android 将内容视图添加到对话框中,android,listview,Android,Listview,我尝试向对话框中添加一个Edittext和一个ListView。 我使用dialog.addContentView(lstcontent,params)方法将视图添加到对话框中 这是我的密码: dialog = new Dialog(MainActivity.this); final LinearLayout.LayoutParams lp = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.Layou

我尝试向对话框中添加一个
Edittext
和一个
ListView
。 我使用
dialog.addContentView(lstcontent,params)
方法将视图添加到对话框中

这是我的密码:

dialog = new Dialog(MainActivity.this);

final LinearLayout.LayoutParams lp = new
LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);

dialog.addContentView(edittext, lp);
dialog.addContentView(listview,lp);

dialog.show();
但是我的listview在edittext上。我想在listview的上方设置edittext

我也用了这个:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2);
LinearLayout layout = new LinearLayout(G.context, (AttributeSet) params);

layout.addView(input);
layout.addView(lstcontent);
dialog.setcontentView(layout);
但这个崩溃的应用程序:
LayoutParams不能转换为android.util.Attributeset

使用dialog.setContentView(R.layout.yourlayout)和使用自己的布局可能会更容易

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
然后

   params.addRule(RelativeLayout.BELOW, id);
更多信息

//编辑

RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(layoutParams);

RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params2 = new 
RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

params1.addRule(RelativeLayout.ABOVE, LISTVIEW_ID);
params2.addRule(RelativeLayout.BELOW, EDITTEXT_INPUT_ID);

layout.addView(EDITTEXTID, params1);
layout.addView(LISTVIEW, params2);

现在你必须为你的对话框设置这个布局,它应该可以工作了

我找到了解决这个问题的新方法

LayoutInflater inflate2 = ((Activity) G.context).getLayoutInflater();
View dialogView = inflate2.inflate(R.layout.layout_dialog, null);

input = (EditText) dialogView.findViewById(R.id.edt1);
lstcontent = (ListView) dialogView.findViewById(R.id.lst1);

lstcontent.setAdapter(adapter); 
这是
layout\u dialog.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="match_parent"
android:orientation="vertical" >
<EditText 
    android:id="@+id/edt1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />
<ListView 
    android:id="@+id/lst1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >    
</ListView>


为什么不从xml中将活动的主题设置为对话框。只需开始使用intent即可。它将显示为对话框。您可以将视图设置为Ank you,但我在转换参数时出错LayoutParams无法转换。再次查看我的问题,我编辑过,有什么理由用java而不是xml创建布局吗?我认为如果采用xml的方式会更容易