---
title: "Android AlertDialog动态添加组件和padding靠边问题"
author: "fonter"
date: "2010-08-09T11:30:29Z"
tags: []
categories: ["移动开发"]
slug: "android-alertdialog-padding"
draft: false
lastmod: "2010-08-09T11:30:29Z"
id: 732774
url: "https://fonter.iteye.com/blog/732774"
---

先上图

 

![](http://dl.iteye.com/upload/attachment/290116/027fbd12-cd1b-333a-a278-d300ecc0f36e.png)

 

 

AlertDialog有个问题是动态添加组件时，组件会很靠边框，这样很不好看，下面这个方案是解决这个问题

 

 

```
		LayoutInflater mInflater = (LayoutInflater) getContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = mInflater.inflate(R.layout.recordlayout, null);
		LinearLayout layout = (LinearLayout) view
				.findViewById(R.id.id_recordlayout);
		for (int i = 0; i < fieldName.length; i++) {
			String name = fieldName[i];
			if ("_id".equals(name))
				continue;
			TextView tv = new TextView(getContext());
			tv.setText(fieldName[i]);
			EditText edit = new EditText(getContext());
			layout.addView(tv);
			layout.addView(edit);
		}

		AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
		dialog.setTitle(R.string.add_a_record);
		dialog.setView(view);

		dialog.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {

					}
				});
		dialog.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {

					}
				});
		dialog.show();
```

 

 

```
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent" android:layout_height="fill_parent">
	<LinearLayout android:id="@+id/id_recordlayout"
		android:layout_width="fill_parent" android:layout_height="fill_parent"
		android:orientation="vertical" android:padding="10dip"></LinearLayout>
</ScrollView>
```