简体   繁体   中英

What is the best way to organize android development code?

I know that every situation will be different, but I just wanted see if there was a general recommendation.

Currently, I have my activities (screens) dynamically creating custom button objects and custom edit text objects. Each of these objects have listeners to see if their state has changed. These object classes have all the logic for the screen. The activity's only job is to assign objects to the widgets I created in XML.

Part of me thinks it should be opposite, where the activity contains all the logic for all the widgets on the screen and simply waits for the objects to notify it when the listeners go off.

Which way is more "standard" ?

I use the following way. I have a common EventHandler sub class in every activity or fragment and I add a single instance belonging to activity to each UI item. EventHandler implements OnClickListener, OnChanged.., and so on.

I would also recommend looking at this library, if you are familiar with DI concept:

https://github.com/roboguice/roboguice/

Here is an example of code of mine:

package com.x.y;

public class DashboardActivity extends FragmentActivity {

    private EventHandler eventHandler = new EventHandler();

    @SomeAnnotationForInit(R.id.some_id)
    private Button feedButton;

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

        initGui();
    }

    private void initGui() {
        feedButton.setOnClickListener(eventHandler);
    }

    private class EventHandler implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            if(view.equals(...)) {
                //TODO:
            }
        }
    }
}

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