Calling findViewById() from outside an activity

后端 未结 4 1301
天涯浪人
天涯浪人 2021-01-17 12:58

Is there any way to access a layout\'s view from a non-Activity-derived class? I\'m creating an Accordion class and need to access some of the activity\'s UI elements. I\'

4条回答
  •  离开以前
    2021-01-17 13:46

    Here is something that might be helpful.

    public interface IViewRequest {
    
        public View requestViewByID(int id);
    }
    
    public class MyActivity extends Activity {
    
        private IViewRequest viewRequest = new IViewRequest(){
    
        public View requestViewByID(int id){
            return findViewById(id);
        });
    }
    
    public class Accordion(){
    
        private IViewRequest viewRequest;
    
        public Accordion(IViewRequest viewRequest){
            this.viewRequest = viewRequest;
        }
    
        private View findViewById(int id){
            return viewRequest.requestViewByID(id);
        }
    }
    

    I have never tried something like this. I also don't know if it won't cuase any memory leaks. But it does what you asked :) "Calling findViewById() from outside an activity"

提交回复
热议问题