2012-06-28 27 views
5

Tôi đang cố gắng tạo bộ chọn hình ảnh phổ quát cho nhiều nút. Có tùy chọn thay đổi tài nguyên "android: drawable" của xml từ mã java không?Thay đổi giá trị bộ chọn xml từ mã java

+0

mà kiểm soát bạn muốn thiết lập tài nguyên drawable. ví dụ. Nút hoặc chế độ xem văn bản – rajpara

Trả lời

25

sử dụng StateListDrawable cho seeting selector bằng mã như:

StateListDrawable states = new StateListDrawable(); 
states.addState(new int[] {android.R.attr.state_pressed}, 
    getResources().getDrawable(R.drawable.pressed)); 
states.addState(new int[] {android.R.attr.state_focused}, 
    getResources().getDrawable(R.drawable.focused)); 
states.addState(new int[] { }, 
    getResources().getDrawable(R.drawable.normal)); 

imageView.setImageDrawable(states); //YOUR IMAGE HERE 
//AND FOR BUTTON 
button.setBackgroundDrawable(states);//FOR BUTTON 
+0

imageView? tôi có cần thiết lập một cái trong bố cục của mình không? – TalMihr

+0

có khi nhu cầu của bạn tạo động hoặc thêm bố cục Imageview vào Xml –

+0

làm cách nào để tự động thực hiện? – TalMihr

3

Bạn có thể đặt nút drawable từ java như

btnSettings.setBackgroundResource(R.drawable.ic_launcher); 
Các vấn đề liên quan