Question

I have a typical dual UI scenario - a list of categories, which when one is clicked, loads a category detail fragment containing a list of items in that category. On the phone, it's implemented as a stack-of-cards UI, opening up the details in a separate activity on top of the category list. On a tablet, it's the category list on the left, with the details on the right.

In the details pane, there's a button to add an item. The details fragment has an interface, required of Activities, with an onClickAddItem method, which should bring up a DialogFragment to ask you for the details of the item and add it when it returns.

The problem: both the tablet version's all-in-one Activity and the phone's standalone details Activity need the same onClickAddItem logic. There's a sinking feeling deep in my gut that the proper solution for this is to pull that logic out into yet another class, but the need to create several million files to do simple things in Android is slowly driving me insane, so I'm hoping there's another best practice I'm overlooking here. Thanks!

Was it helpful?

Solution

If your "add" button is in the detail fragment, there is no reason to handle the click event in the activity. I think you should put the click event handling in your detail fragment.

Why do you want to keep all database access in the activity ? Make sure you're properly abstracting database access ( using a ContentProvider for example ) and don't be shy to use your abstraction wherever it makes sense. Adding an item using a ContentProvider should be as simple as:

getContentResolver().insert(myUri, myNewItemContentValues);

It you need to display a dialog, just get a reference to the current activity from the detail fragment, and use it to display your dialog.

If several fragments share the same functionality, you may need to write a simple helper class with some methods like:

public void showAddItemDialog(Activity activity)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top