Android View.setId(int id) 用法


Android View.setId(int id) 用法

當要在代碼中動態的添加View並且為其設置id時,如果直接用一個int值時,Studio會警告.
經過查詢,動態設置id的方法有兩種;

1. View.generateViewId();

這個方法的返回值是個int值,方法的意思是獲取一個可以用在setId(int id)方法中的int類型id;

官方文檔說明:

int generateViewId () 						Added in API level 17
Generate a value suitable for use in setId(int). This value will not collide with ID values generated at build time by aapt for R.id.
Returns int  a generated ID value

缺點是,你需要用一個變量去記錄此id,第二就是它是api17才加入的方法

2.在xml中定義id

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="id_add_file" type="id"/>
</resources>

使用就很簡單:

imageView.setId(R.id.id_add_file);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM