簡體   English   中英

在運行時獲取自定義按鈕資源ID

[英]Getting Custom Button Resource ID At Runtime

我在res / drawable文件夾中有一個名為“ mybutton.xml”的自定義按鈕。 在運行時,我正在運行時創建一個按鈕,如下所示:

Button myButton = new Button(this);

myButton.setBackgroundResource(?); // <--- This line is where I need help

我想做的是將我的按鈕名稱“ mybutton.xml”動態解析為可以傳遞給setBackgroundResource的資源,以便該按鈕將使用我的自定義按鈕。 我該如何在android中做到這一點?

您只需要myButton.setBackgroundResource(R.id.mybutton),其中R.id.mybutton id與XML中的按鈕id匹配。

我想到了。 萬一其他人需要這樣做,下面是代碼:

Button myButton = new Button(this);

myButton.setBackgroundResource(getResources().getIdentifier("myButton", "drawable",this.getPackageName()));

希望這可以幫助其他人!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM