简体   繁体   中英

How can I initialize my RelativeLayoutButton outside of onCreate method?

I'm creating a landing page with a series of buttons for other activities. LandingActivity extends a custom BaseActivity. The buttons have their own RelativeLayout with an image and some text with a LandingButton class to handle them. Right now, everything works so long as my buttons are declared and customized all within onCreate. I would like to compartmentalize a little bit more.

I have tried declaring them before onCreate, initializing them inside my initViews() method and calling that inside onCreate as I would with any standard view.

public class LandingActivity extends BaseActivity {

    LandingButton bMyData = new LandingButton(this, R.id.myDataButton);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout)
    //initViews();

This results in a NullPointerException pointing me to the LandingButton.java

public LandingButton(Context context, int id)
{
    super(context);

    if (!(context instanceof Activity))
        return;

I have also tried changing my LandingButton to reference BaseActivity instead of Activity:

    if (!(context instanceof BaseActivity))
        return;

Same error. App crashes during debug as soon as it hits onCreate without giving me much to go on.

Ideally, I would like to declare my LandingButtons before onCreate, and edit them within initViews() to keep my onCreate method neat if possible.

You cant initialize your views before onCreate because this is where your activity is starting.

You cant initialize something within your activity class before you have already initialized activity.

So if you want to extract your initializations to method simply call this method inside onCreate :

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout); 
    initViews();
}

From the documentation :

Called when the activity is starting. This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM