문제

What techniques do you use to keep files from getting too large? What refactorings do you use to break down large files?

I find that some files in my Android project get very large simply by the nature of the language and platform. For example, my main activity sets up an action bar, a drawer, options menu, and a click listener for each. Of course, that file also implements several inherited methods... next thing you know, the file ends on line 1500.

Since everything I'm bringing up to that file needs to be a concrete implementation, I'm having a hard time conceptualizing how I could abstract some of the stuff in it away from the file.

One thing I have tried is to separate some of the private inner classes into an Impl class, only so each file is smaller and more manageable:

// Instead of putting this inside MainActivity.java
private class DrawerItemClickListener implements ListView.OnItemClickListener
{
    ...
}

// It's now in a separate file as - very specific class
public class DrawerItemClickListenerImpl implements ListView.OnItemClickListener
{
    ...
}

While this helps to break down the size of the one file, it feels weird creating classes that are only used once, and for a very specific reason...

도움이 되었습니까?

해결책

This is really the nature of UI programing and it is no different than java swing programming.

In that paradigm, you have a JPanel, with some buttons, some combo boxes and some listeners. You have to implement listeners to those elements but only that JPanel really has use for them. So, you implement inner classes as listeners so everything on that panel interacts well.

Having something like

public class IpAddressPanelListener implements ActionListener

as a public class misses the whole point. Public classes are about sharing usability. Inner classes are about classes that are super-specific to the job. Which, in the case of a UI is generally what you have

if you really need to break them out cause you can't conceptualize it all then what you could do is put them (and the Activity Class impl) into their own package and declare all classes and methods as package scope. Now you can have your files broken out without making them available to the general public

다른 팁

One good Android design pattern is to use fragments: http://developer.android.com/guide/components/fragments.html.

At a very high level, fragments are classes for re-usable components in your Android application. Fragments also offer other benefits. One of the most notable is the ability to build adaptive UIs - that is UIs that make the best use of available screen real estate. When you design your app with fragments, the role of your activity becomes the management of these fragments (e.g. providing data, interrogating them for user input, etc).

There are many good tutorials for fragment design out there.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top