程序布局问题,高度不正确

时间:2015-04-25 00:57:33

标签: android toast

我尝试创建自己的Toast,并通过以编程方式创建布局,然后将布局设置为Toast的视图来进行此布局。

这对我的大部分代码都非常有用,但我遇到了一个我似乎无法解决的非常具体的问题。

我尝试将图像添加到吐司中,然后在文本下方或上方显示该图像。
在文本上方添加图像时,这可以100%正确工作。这在下面的第一张图中显示:
http://i58.tinypic.com/zn2ag3.png

但是当我尝试将图像添加到底部时,所有地狱都会松动,我最终会这样: http://i59.tinypic.com/vdnyoj.png

这是我的代码:

private void showToast() {
    //Variables
    Context context = getActivity();
    int imageGravity = Gravity.BOTTOM;
    CharSequence text = "Test";

    //Create parent layout
    RelativeLayout relativeLayout = new RelativeLayout(context);
    RelativeLayout.LayoutParams relLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    relativeLayout.setLayoutParams(relLayoutParams);

    //Set background color
    relativeLayout.setBackgroundColor(0xFFF44336);

    //Set padding
    int padding = 10;
    relativeLayout.setPadding(padding, padding, padding, padding);

    //Initialize image
    ImageView imageView = new ImageView(context);
    int imageViewId = 0x100;
    imageView.setId(imageViewId);
    imageView.setAdjustViewBounds(true);
    imageView.setImageResource(R.drawable.default_person_image);
    RelativeLayout.LayoutParams imageViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    int margin = 30;
    if(imageGravity == Gravity.TOP) {
        imageViewParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        imageViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        imageViewParams.setMargins(0, 0, 0, margin);
    } else if(imageGravity == Gravity.BOTTOM) {
        imageViewParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        imageViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        imageViewParams.setMargins(0, margin, 0, 0);
    }

    relativeLayout.addView(imageView, imageViewParams);

    //Initialize textView
    TextView textView = new TextView(context);
    int textViewId = 0x101;
    textView.setId(textViewId);
    textView.setText(text);
    textView.setTextColor(context.getResources().getColor(android.R.color.white));
    RelativeLayout.LayoutParams textViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    if(imageGravity == Gravity.TOP) {
        textViewParams.addRule(RelativeLayout.BELOW, imageViewId);
    } else if(imageGravity == Gravity.BOTTOM) {
        textViewParams.addRule(RelativeLayout.ABOVE, imageViewId);
    }

    relativeLayout.addView(textView, textViewParams);

    //Setup the toast
    Toast toast = new Toast(context);
    toast.setView(relativeLayout);
    toast.show();
}

我希望有人可以发现我的代码有什么问题,因为我自己无法找到问题。

0 个答案:

没有答案