Using inheritance for encapsulation with Android Views - android

I'm trying to get into Android development on Android development's terms. To this end, I don't want to push onto it a mental model that is largely based on WinForms development.
My problem is that I find Activities and their fragments too cluttered. There are interface implementations all over the place. There are type hierarchies that get smushed into my Activity files. I find it, to say the least, off putting. When I see examples on the developer.android.com site they seem to advocate this complex, everything in one massive file model.
At the same time, I realize that the demo code is just that, demo code. What's the right approach when working with Android elements?
For example, I would like to have a GridView to display some graphics and allow the user to click on them, or long press on an item to do something. I can do this within an Activity.java file, within a public static class Fragment nested in the Activity.java file. I can then implement the on tap and hold listeners. At this point, I feel that this is a rather muddy design.
Would it be Android-Idiomatic to have instead a class that that extends GridView with my specific implementations of the listeners? In this instance, if the GridView decided to navigate somewhere, it could.
The question really applies to any complex view within Android. ListFragment seems nicer since at least I'm getting a type hierarchy explicitly here. I can have the fragment react to various item events.

Related

Android Best Pratice to reuse code and layout

I've been reading about the include tag on xml, fragments to use on layout for smartphone and tablets but I'm getting more confused than getting a solution to my problem.
My App has 4 screens.
1 - You login and it download info from a json
2,3,4 - From login, Activity 2 load (A list with custom adapter), where you can click one of 2 images to jump to 3rd and 4th activity.
I need now to create the activity 1, 2, and 3 again with different JSONs being parsed, with 1 and 2 having the same layout of the existent ones and 3 with a different layout.
The code I need for them to work is(or can be) the same (Download Task with AsyncTask, button click listeners, etc) I already have for those activities.
I think it's not a goot pratice to copy basically the same getView method, for example, and paste on a new class, right? The buttons wouldn't work on the second range of screens for example.
So, what approach should I take that isn't copy and paste code and change things manually?
Sorry for the newbie question.
If needed I can provide code.
PS 1: I've already did tests with include on xml and copy code but that doesnt look professional
PS 2: Is fragments only for different screens like tablet or I could make something with it?
That's several questions, so here's several answers, including to some un-asked questions:
To the greatest extent possible, strive to remove as much code as possible from your Activities, Fragments, etc. If it doesn't have anything to do with the Android lifecycle or actually putting something on the screen (e.g. parsing JSON), put it in a "plain old java" class. Also, this way, you can share the functionality among Activities.
IMHO, you should never use an AsyncTask, for any reason. They're used with an Activity or Fragment, but don't respect the Fragment or Activity lifecycle, so are often the cause of crashes that can be difficult to diagnose. Use something synchronized with the lifecycle, like a Loader. Or go the RxJava route, where Subscribers can be canceled at the appropriate point in the Activity/Fragment lifecycle.
Fragments can be good for code re-use, but they have a slightly different lifecycle from Activities, so they can be difficult to work with, so use them sparingly and be careful. If you're doing it just to re-use a bit of UI (but not behavior), a layout "include" is probably better. For behavior, a custom View class can be a good alternative to a Fragment.
Don't do HTTP / REST access yourself, using primitives like HTTPUrlConnection. There are a lot of corner cases that are going to get you into trouble. Use one of the several really good open-source libraries that are built for this purpose. I highly recommend Retrofit.

Android: Widget, AppWidget, Fragment, Activity and App - What's the difference?

I've got a lot of experience with Java and C#, but I'm new to Android. I mainly use C# because I am enamored of the Control hierarchy. I love the plug-and-play of the ontology. I'm trying to understand the ontology in this new paradigm and I may have been given some false information.
With respect to Apps, that should be the largest component. Within the App, there may be several Activities. An activity can display a number of Fragments. AppWidgets appear to be a special case as they exist as a component of the App, but are shown on their own. And I was told that you can extend Buttons or ProgressBar to create your own components which again appear to be called Widgets.
As I said, I may have this completely wrong. Ideally I would like to create my own widgets which I can put on a Fragment, an AppWidget or an Activity; any of which I might compose into an App. All the online sources I've found only discuss Widget in the sense of an AppWidget? Was I given incorrect information? Can anyone clarify the ontology?
Thanks
"Widget" is a bit of an overloaded term. You will probably have better luck if you search for tutorials on "custom Views" instead. I'll include a brief rundown of various terms and what they mean at the bottom.
A custom View is pretty much anything that extends the View class (or any of its subclasses) and isn't part of the framework. Custom views can be used wherever typical Views are expected, e.g. in layout files or directly constructed in Java. One thing to note: only certain Views can be used in an AppWidget because they are running in another process outside of your app. This means your custom Views cannot be used in AppWidgets. In my experience this tends not to matter too much.
App: An application. Contains components, which are defined in the manifest within the <application> tag.
Activity: One of the four application components. Nearly always has an associated UI, composed of a hierarchy of Views.
Fragment: A framework class that helps modularize your application's code and UI. Fragments can be attached to an Activity and can contribute some UI to the View hierarchy of the Activity. They are entirely optional; you don't have to use Fragments in your app, and you can attach a Fragment without it contributing any UI to the Activity.
View: A UI component, such as text (TextView) or images (ImageView). These are also referred to as "widgets", and you may notice the framework classes are found in the android.widget package. Some views contain other views, so that you can build a UI hierarchy; these will extend ViewGroup and are referred to as "view groups" or "layouts" more or less interchangeably.
AppWidget: Something the user can add to his or her homescreen. This is provided by the app, but is not one of the 4 application components mentioned previously (it is managed by an application component, namely a special subclass of BroadcastReceiver). Most people colloquially refer to these as "widgets" because it's shorter to say and launchers used that terminology as well, thus conditioning users to it.

Do fragments cause fat activities?

Recently I was given the task of building an app which is rather like a book. The high-level design was basically a couple of list views showing chapters, then drill-down into a list of topics then onto a page itself. There were a number of other list-type views which displayed bookmarks or text search results and there was a fair amount of animation, sliding one fragment off and another on at the same time. This was my first use of fragments and although they first appear to be a good encapsulation of a piece of UI functionality, I can't help wondering if their use, as in my case, leads to 'fat' Activity classes, having to manage several different fragments and having to implement several interfaces which they publish.
As an example showing the interfaces implemented by one Activity:
public class NodeListActivity extends Activity implements
NodeListFragment.OnItemSelectedListener,
SearchListFragment.OnItemSelectedListener,
NodeFragment.OnLinkSelectedListener,
OnCloseSelectedListener,
OnActionBarItemSelectedListener,
OnBookmarkSelectedListener
On older versions of Android, I would have created a separate Activity for each main screen/function.
Is this a code smell or does the combination of several fragments and animations lead to fat Activities?
does the combination of several fragments and animations lead to fat Activities?
Yes. However, that is becoming more common, and therefore less code smelly.
What is somewhat smelly is that loooooooooooooooooooong list of interfaces. :-)
For something that complex, you might find that using an event bus (Square's Otto, greenrobot's EventBus, or even LocalBroadcastManager) is a cleaner approach. Rather than having fragments use an interface to tell their hosting activity about an event (which is my guess as to the source of all your interfaces), the fragment can post an event to the bus, which the hosting activity can subscribe to. This does add a smidge of runtime overhead, but adds the benefit of avoiding all the interfaces. It can also be extended to other components, such as a service posting an event when something happens in the background that the UI layer, if it exists, needs to know about.

Tips on refactoring an Android prototype

I have an Android project I've inherited from another developer.
The original code was hacked together using a single View and a single Activity. The view class has a State variable that is switched on during input and rendering.
Each "screen" is a single bitmap rendered directly onto the screen. There are no layouts used at all. To make things even worse each variable in both the View and Activity classes were all declared public static and would access each other frequently.
I've reworked the code so it is now somewhat manageable, but it's still in those original two classes. This is my first decently sized Android app so I'm not completely sure where to go next.
From the looks of things, each "screen" should have its own View and Activity. Is this the general practice?
If so I need some way to share data between the separate Activities. I've read suggestions to use a Singleton class that holds generic data. Is there any other ways that are more built into the Android framework?
Thanks in advance.
I would recommend using one activity per screen, or rather, per function. An activity generally has one associated view that draws the UI. If all the activity does is display different bitmaps, than you can define an ImageView in the layout and display the various bitmaps in that ImageView.
Using public static fields is bad practice in Android Activities. Activities should not access fields in other Activities at all, they should pass data to one another through the intent, or via a database, or via shared #Injected classes.
From what you write, it may be easier to start that app again from scratch, than to try to fix the current app. I have been there, done that, afterwards regretting not scrapping the app and starting from scratch.

About Architecture Application

I have a technical problem about my architecture. I explain my goal with this project.
I want to create a modular application. So I have created several modules; some have a UI and others do not.
My UI application is divided in three parts:
one part, is the header, which display hours and some technical information
another part is a list view where we can select the module to display.
the final part is the content of the module or the default screen.
So I tried to explore fragment where each item of my listview is a fragment. According to user's click, I load and display the view of the module in the content.
Each module do its treatment when it receives a intent from a broadcast.
An other idea, is to create, one view per module and attach this view to my current view (not create dynamically but with an xml).
I am so confused with the type of architecture to use.
If anyone has suggestions.
This sounds like an ideal use for fragments. The guide topic on fragments explains the general approach and also discusses FragmentLayout.java, which is part of the API Demos sample project.

Categories

Resources