Java 在按钮/文本视图上使用getDimension()总是返回相同的值

Java 在按钮/文本视图上使用getDimension()总是返回相同的值,java,android,button,dpi,Java,Android,Button,Dpi,我正在为android平板电脑制作一个专用的应用程序,其中一部分有基于各种新闻标题动态创建的按钮。我有一个dimens.xml,我使用DisplayMetrics中的比例因子使大小适合不同的密度。问题是,当我在xml中更改大小时,它对方法返回的维度绝对没有影响 RelativeLayout.LayoutParams announcementButtonLayout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WR

我正在为android平板电脑制作一个专用的应用程序,其中一部分有基于各种新闻标题动态创建的按钮。我有一个dimens.xml,我使用DisplayMetrics中的比例因子使大小适合不同的密度。问题是,当我在xml中更改大小时,它对方法返回的维度绝对没有影响

RelativeLayout.LayoutParams announcementButtonLayout = new   RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
announcementButtonLayout.topMargin = topMargin;
announcementButtonLayout.addRule(RelativeLayout.ALIGN_PARENT_TOP);
announcementButtonLayout.height =     this.getResources().getDimensionPixelSize(R.dimen.news_button_height);
announcementButtonLayout.width = getResources().getDimensionPixelSize(R.dimen.dashboard_right_width);

Button button = new Button (this.getActivity());
button.setWidth(getResources().getDimensionPixelSize(R.dimen.dashboard_right_width));
button.setBackgroundResource(R.drawable.photo_edited);
button.setTextColor(getResources().getColor(R.drawable.news_poll_item_text_color));
float f =Utilities.getPixelScaleMultiplier();
f *= getResources().getDimension(R.dimen.news_item_text);
button.setTextSize(f);
button.setText(announcement.getDescription());
button.setMaxLines(1);
button.setTag(announcement);
button.setOnClickListener(this);            
button.setLayoutParams(announcementButtonLayout);
button.setId(index);
根据我上面的按钮代码,是什么导致了这种信任违约

谢谢

阿杜尔纳里


编辑:包含我的LayoutParams作为参考

使用LayoutParams设置视图宽度和高度,然后将其添加到视图组

Button button = new Button (this.getActivity());
//button.setWidth(getResources().getDimensionPixelSize(R.dimen.dashboard_right_width));
button.setBackgroundResource(R.drawable.photo_edited);
button.setTextColor(getResources().getColor(R.drawable.news_poll_item_text_color));
float f =Utilities.getPixelScaleMultiplier();
f *= getResources().getDimension(R.dimen.news_item_text);
button.setTextSize(f);
button.setText(announcement.getDescription());
button.setMaxLines(1);
button.setTag(announcement);
button.setOnClickListener(this);    
LayoutParams announcementButtonLayout = new LayoutParams(getResources().getDimensionPixelSize(R.dimen.dashboard_right_width), LayoutParams.WRAP_CONTENT);        
button.setLayoutParams(announcementButtonLayout);
button.setId(index);

更改dimens.xml值后清理项目,可能您的案例中没有更新R文件。

尝试使用按钮。setBounds找到了解决方案:


“清理”是将我在xml中更改的值添加到页面的后面部分,这些值以前位于该部分。较低的一个在指定大小。

Do announcementButtonLayout.width=getResources().getDimensionPixelSize(R.dimen.dashboard\u right\u width);不用setWidth(),谢谢你的提示,但那没用。抱歉,hbansal,清理不起作用,但是“params”应该做什么?我是否应该将这些参数用于我的announcementButtonLayout?LayoutParams在布局和测量过程中定义视图边界(高度、宽度、边距等)。编辑我的回答我是说你定义的第二个。所有这些都已经在上面设置好了。将宽度定义为参数而不是通过字段真的会改变它吗?按钮没有设置边界?