需求:Button宽度为match_parent,因此宽度不定,但要根据背景图片的长宽比来调整Button大小使其适应背景图。
之前采用的方法是OnGlobalLayoutListener, 不过这样会导致同一个页面的EditText在修改文字时不改变文字。
Button completeButton = (Button)findViewById(R.id.completeButton);
completeButton.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
public void onGlobalLayout()
{
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.button_long);
double ratio = ((double)bitmap.getHeight()) / bitmap.getWidth();
ViewGroup.LayoutParams params = completeButton.getLayoutParams();
params.height = (int)(completeButton.getWidth() * ratio);;
completeButton.setLayoutParams(params);
}
});
DisplayMetrics metrics = getResources().getDisplayMetrics();
int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, metrics);
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.button_long);
double ratio = ((double)bitmap.getHeight()) / bitmap.getWidth();
ViewGroup.LayoutParams params = <span style="font-family: Arial, Helvetica, sans-serif;">completeButton</span><span style="font-family: Arial, Helvetica, sans-serif;">.getLayoutParams();</span>
params.width = metrics.widthPixels - padding * 2;
params.height = (int)(params.width * ratio);<pre name="code" class="java">completeButton.setLayoutParams(params);
这样就可以了!