2017-08-27 46 views
0

我在想,我怎麼能得到任何當前視圖屬性?例如,我創建一個按鈕,在代碼中更改它的屬性(顏色,高度等),並且我想以字符串形式返回。如何獲取任何當前視圖屬性?

是否有機會得到我想要的任何屬性,如:知名度,背景,layout_width,layout_height,重力,minWidth等

如何快速做到這一點,我應該使用監聽器用於此目的?

+0

你目前的看法是什麼意思? –

+0

只需使用'button.get ..()'獲取任何數據 –

回答

1

如果我理解正確的話,這裏是代碼,允許你在字符串獲得一些屬性:

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)返回大小。

+0

謝謝!它對我很好。但還有一件事,當我要求ID時,我收到了int值,比如「2131427422」而不是字符串值,這是我在屬性中設置的值。如何轉換它? –

+0

如果答案有幫助,請將其標記爲「答案」。 – SolderingIronMen

+0

對於第二個問題,請使用此方法:https://stackoverflow.com/a/14648102/6334198 – SolderingIronMen

0

您需要在View上使用Listener操作,然後獲取您希望在單擊該視圖時檢查的屬性。

舉例一個TextView和獲取它在對TextView中點擊屬性:

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 
+0

點擊監聽器是不必要的 –

+0

我知道。但是我想知道,如果問題提出者想要在用戶觸摸時選擇特定視圖的屬性。至少這是我從問題的最後一句中理解的。 – 2017-08-27 15:55:12

相關問題