user3519023 user3519023 - 10 days ago 5
Android Question

Android: How to execute a method before the layout is initiated/created in an activity

I need to execute a method before initiating the layout in an activity. If I call the method I need to execute inside onCreate(), would it be executed before the layout is set?

The reason is because I need the method to return a piece of information that is displayed in the layout before initiating it. Would love some feedback on this.

Answer

You can do whatever you like before setContentView like so:

public class TestActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int i = 0;
        setContentView(R.layout.main);
    }
}

As long as you do not interact with views that have not been inflated yet

For example this is an error:

public class TestActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ERROR, CAN'T TOUCH UI ELEMENTS
        ImageView img = (ImageView)findViewById(R.id.img);
        setContentView(R.layout.main);
    }
}