如何获取任何当前视图属性?



我想知道,如何获取任何当前视图属性?例如,我创建一个按钮,在代码中更改其属性(颜色、高度等(,我想将其作为字符串返回。

有没有机会获得我想要的任何属性,例如:可见性、背景、layout_width、layout_height、重力、最小宽度等。

我怎样才能快速做到这一点,我应该为此目的使用侦听器吗?

如果我理解正确,这里是代码,它允许您获取字符串中的一些属性:

Button button = (Button) findViewById(R.id.button);
String visibility = String.valueOf(button.getVisibility());
String width = String.valueOf(button.getWidth());
String height = String.valueOf(button.getHeight());

请注意,getWidth(( 和 getHeight(( 方法以像素为单位返回大小(不是 dp(。

您需要对视图使用侦听器操作,然后获取要在单击该视图时检查的属性。

文本视图的示例,并在单击该文本视图时获取其属性:

TextView tv = (TextView) findViewById(R.id.textView);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ColorDrawable cd = (ColorDrawable) tv.getBackground();
int colorCode = cd.getColor();//colorCode in integer
}
});

如果您只想访问视图的属性,则可以通过调用要访问的属性来访问它,例如:

TextView tv = (TextView) findViewById(R.id.textView);
ColorDrawable cd = (ColorDrawable) tv.getBackground();
int colorCode = cd.getColor();//colorCode in integer

最新更新