二、view. Window .setContentView( View view)。主要代码如下:LayoutInflater inflater = LayoutInflater.from(Context context); View view = inflater.inflate(R.layout.alertdialog, null);//这里的R.layout.alertdialog即为你自定义的布局文件
关于两者的区别,大家可以看这个链接: http://www.x2x1.com/show/6040883.aspx 。AlertDialog mAlertDialog = builder.create(); mAlertDialog.show(); mAlertDialog.getWindow().setContentView(view);
但是这段代码同样需要放在 show()的后面,不然你的改动会没有效果。mAlertDialog.getWindow().setLayout(150, 320);
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/alertdialog" android:layout_width="match_parent" android:layout_height="40dp" android:orientation="vertical" > <TextView android:id="@+id/titleView" android:layout_width="match_parent" android:layout_height="40dp" android:background="#006600" android:gravity="center" android:singleLine="true" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:focusable="true" android:selectAllOnFocus="true" /> <ListView android:id="@id/android:list" android:layout_width="match_parent"
android:layout_height="wrap_content" android:background="#666633" android:gravity="center" /> </LinearLayout>
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text2" android:layout_width="150dip" android:layout_height="40dip" android:layout_gravity="right" android:textSize="18dip" android:textColor="#000000" android:background="#b0556B2F" android:gravity="center_vertical" />
最后效果:private void showAlertDialog() { String[] itemList = {"设为铃声", "移除", "歌曲信息", "添加到..."}; ListAdapter mAdapter = new ArrayAdapter(context, R.layout.item, itemList); LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.alertdialog, null); TextView titleView = (TextView)view.findViewById(R.id.titleView); String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)); titleView.setText(title); ListView listview = (ListView)view.findViewById(android.R.id.list); listview.setAdapter(mAdapter); listview.setOnItemClickListener(listener); AlertDialog.Builder builder = new AlertDialog.Builder(context); AlertDialog mAlertDialog = builder.create(); mAlertDialog.show(); mAlertDialog.getWindow().setContentView(view);
mAlertDialog.getWindow().setLayout(150, 320); }