2

已解决:见下方答案

我将 Dialog 子类化以创建具有自定义背景的对话框。我在对话框中添加了一个子类视图,它正在正确绘制位图背景和布局。但是按钮不会响应任何触摸事件。

我怀疑必须在 Dialog 类中加载 LinearLayout,但我认为我必须在视图类中加载它才能在位图上绘制。

我对 Android 开发者完全陌生,所以我为这个问题道歉。这是我正在做的事情:

public class CustomDialog extends Dialog {

private static final String TAG = "CustomDialog";
private static int layoutWidth = 640;
private static int layoutHeight = 400;

public CustomDialog(Context context) {

    super(context, android.R.style.Theme_Translucent_NoTitleBar);

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    LayoutParams params = getWindow().getAttributes(); 
    params.width = LayoutParams.FILL_PARENT;
    getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);

//      setContentView(R.layout.layout_dialog); // This works fine, the buttons work
    setContentView(new NewLayoutDialogView(context));
}

public static class NewLayoutDialogView extends View {

    private Drawable bg;
    public LinearLayout layout;
    private OnColorChangedListener mListener;

    public interface OnBrushChangedListener {
        void brushChanged(float radius);
    }

    NewLayoutDialogView(Context context) {  

        super(context);

        InputStream stream = getResources().openRawResource(R.drawable.dialog_bg);
        bg = NinePatchDrawable.createFromStream(stream, null);

        layout = (LinearLayout) LinearLayout.inflate(context, R.layout.layout_dialog, null);

        Button ok = (Button) layout.findViewById(R.id.ok_button);

        layout.setWillNotDraw(false);

        layout.setVisibility(View.VISIBLE);
        setVisibility(View.VISIBLE);

        layout.measure(layoutWidth, layoutHeight);
        layout.layout(0, 0, layoutWidth, layoutHeight);
    }

    @Override 
    protected void onDraw(Canvas canvas){

        if (bg != null) {
          bg.setBounds(10, 0, canvas.getWidth(), canvas.getHeight());
          bg.draw(canvas);
        }

        layout.draw(canvas);
    }
 }
}

编辑:这就是我设置听众的方式。使用 View 子类时,我必须禁用此代码,如图所示。但是按钮仍应显示单击状态,而无需侦听器。

        Dialog dialog = new ChangeLayoutDialog(getActivity());      

        Button cancel = (Button) dialog.findViewById(R.id.cancel_button);
        cancel.setTypeface(font);
        cancel.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
              dialog.dismiss();
             }
          });

        Button ok = (Button) dialog.findViewById(R.id.ok_button);
        ok.setTypeface(font);
        ok.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
              dialog.dismiss();
              setCellLayout(layoutFile);
             }
          });
4

1 回答 1

1

Instead of adding the subview class and drawing the background, all I needed to do was add:

getWindow().setBackgroundDrawableResource(R.drawable.dialog_bg);

I guess I was just trying way too hard!

于 2011-12-20T08:44:38.407 回答