Android View.setId(int id) 用法
當(dāng)要在代碼中動態(tài)的添加View并且為其設(shè)置id時,如果直接用一個int值時,Studio會警告.
經(jīng)過查詢,動態(tài)設(shè)置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);