Android,在警报对话框中的另一个项目下添加项目

时间:2014-05-17 12:27:53

标签: android android-alertdialog

我想在下面的代码中aEditText下面添加aNumberPicker,目前aEditText出现在提醒的左上角,你将如何设法将其提升到aNumberPicker以下 public void onClickNotes(View view) { Context mContext = this; RelativeLayout linearLayout = new RelativeLayout(mContext); final NumberPicker aNumberPicker = new NumberPicker(mContext); final EditText aEditText = new EditText(mContext); aNumberPicker.setMaxValue(50); aNumberPicker.setMinValue(1); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(50, 50); RelativeLayout.LayoutParams numPickerParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams EditParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); numPickerParams.addRule(RelativeLayout.CENTER_HORIZONTAL); linearLayout.setLayoutParams(params); linearLayout.addView(aNumberPicker,numPickerParams); EditParams.addRule(RelativeLayout.ABOVE, 0); linearLayout.addView(aEditText,EditParams); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext); alertDialogBuilder.setTitle("Entry Index"); alertDialogBuilder.setView(linearLayout); alertDialogBuilder .setCancelable(false) .setPositiveButton("Select", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //aNumberPicker.getValue(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } 1}}

{{1}}

1 个答案:

答案 0 :(得分:0)

尝试改变:

EditParams.addRule(RelativeLayout.ABOVE, 0);

EditParams.addRule(RelativeLayout.BELOW, aNumberPicker.getId());

参考:http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#addRule(int,int)

<强>更新
在获取之前,您还需要直接setId(..)aNumberPicker。 因此,请在aNumberPicker实例化后粘贴此代码:

aNumberPicker.setId(generateViewId());

方法generateViewId()的源代码来自:Android: View.setID(int id) programmatically - how to avoid ID conflicts?

private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
    @SuppressLint("NewApi")
    public static int generateViewId() {
        if (Build.VERSION.SDK_INT < 17) {
            for (;;) {
                final int result = sNextGeneratedId.get();
                // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
                int newValue = result + 1;
                if (newValue > 0x00FFFFFF)
                    newValue = 1; // Roll over to 1, not 0.
                if (sNextGeneratedId.compareAndSet(result, newValue)) {
                    return result;
                }
            }
        } else {
            return View.generateViewId();
        }
    }

当然,您可以将Id设置为特定值,例如1,2,38432,但是您应该避免ID冲突,并且修改此方法(在Android API 17中添加)以用于所有API版本。

希望有所帮助