When to call findViewById in an Activity

前端 未结 2 2017
我在风中等你
我在风中等你 2021-01-28 12:54

I am encountering the following issue. I have the following lines of code :

Spinner domainSpinner = (Spinner) findViewById(R.id.domain);
domainSpinner.setVisibi         


        
相关标签:
2条回答
  • 2021-01-28 13:16

    You should always initialise your views on the OnCreate method in an activity to make sure the view exists when you want to reference it. Like below:

    private Spinner domainSpinner;
    
    @Override
        protected void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            domainSpinner = (Spinner) findViewById(R.id.domain);
        }
    

    Let me know if this helps!

    UPDATE: If you need to use the variable outside of the on create method, then declare a global variable and still initialise it on create, then use it where needed.

    0 讨论(0)
  • 2021-01-28 13:24

    You can try this. Make sure the domainSpinner is initialized on the Main Thread. Also add a condition for setting visibility only when domainSpinner is not equal to null.

    Handler mainHandler = new Handler(context.getMainLooper());
    mainHandler.post(new Runnable() {
    
        @Override
        public void run() {
            Spinner domainSpinner = (Spinner) findViewById(R.id.domain);
            if(domainSpinner!=null) {
               domainSpinner.setVisibility(View.VISIBLE);
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题