0

我正在使用 RelativeLayout 创建一个简单的工具栏

对于按钮图像,我正在使用以下代码,

ImageButton back = new ImageButton(ctx.getContext());
                RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                backLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL);


                back.setLayoutParams(backLayoutParams);
                back.setContentDescription("Back Button");
                back.setId(2);
                try {
                    back.setImageBitmap(loadDrawable("icon_left.png"));
                } catch (IOException e) {
                    Log.e(LOG_TAG, e.getMessage(), e);
                }
                back.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                       //
                    }
                });

用于将其添加到工具栏

toolbar.addView(back);

对于我正在使用的工具栏,

RelativeLayout toolbar = new RelativeLayout(ctx.getContext());
toolbar.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,60));           

问题是按钮图像没有填充到布局参数中。

我尝试使用 setMargin 它可以工作,但它不能随各种屏幕分辨率缩放。

在此处输入图像描述

需要有关如何执行此操作的说明。

4

3 回答 3

2

Try setting the back image as the background - it should be scaled automatically by the Android Operating System. I advise you turn that image into a .9.png so that it doesnt stretch the text, just the button appearance you have.

BTW, awesome looking button there.

EDIT: After looking carefully at your code, i think you can simply replace the code

back.setImageBitmap(loadDrawable("icon_left.png"));

with

back.setBackgroundDrawable(loadDrawable("icon_left.png"));
于 2012-06-27T12:58:52.743 回答
1

它没有填充布局,因为您写道:

RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

你想要什么结果?

于 2012-06-27T13:19:22.647 回答
0

默认情况下,ImageButton它的图像后面有一个按钮背景,就像Button它的文本后面一样。

通过调用setBackgroundDrawable(null)您的代码来禁用背景。

于 2012-06-27T13:02:48.280 回答