Last active
October 9, 2016 17:35
-
-
Save jmsalcido/8cc3f50b774eb938ef81bccc87fe22e7 to your computer and use it in GitHub Desktop.
Android Architecture UI 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ---------------------------------------------------------- | |
// VIEW | |
// ---------------------------------------------------------- | |
// This class represents View layer and also Controller layer | |
// ---------------------------------------------------------- | |
public interface ActivityListener { | |
void showMessage(boolean buttonState, String message); | |
} | |
public class MainActivity extends AppCompatActivity implements ActivityListener { | |
private Button loadButton; | |
private TextView console; | |
// Inject the Controller with your favorite DI framework. | |
@Inject | |
MainController mainController; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
// show views | |
setContentView(R.layout.some_layout_activity); | |
loadButton = (Button) findViewById(R.id.load_button); | |
console = (TextView) findViewById(R.id.console_view); | |
// delegate everything to the controller layer! | |
loadButton.setOnClickListener(view -> { | |
mainController.loadClick(MainActivity.this); | |
}); | |
} | |
@Override | |
public void showMessage(boolean buttonState, String message) { | |
runOnUiThread(() -> { | |
loadButton.setEnabled(buttonState); | |
console.setText(message); | |
}); | |
} | |
} | |
// ---------------------------------------------------------- | |
// CONTROLLER | |
// ---------------------------------------------------------- | |
public class MainController { | |
private final CloudApi cloudApi; | |
public MainController(CloudApi cloudApi) { | |
this.cloudApi = cloudApi; | |
} | |
public void clickLoad(ActivityListener listener) { | |
doOnBackgroundThread(() -> { | |
cloudApi.downloadSomething(listener); | |
}); | |
} | |
} | |
// ---------------------------------------------------------- | |
// MODEL | |
// ---------------------------------------------------------- | |
// Classes that represents the Model layer | |
// ---------------------------------------------------------- | |
public class CloudApi { | |
public void downloadSomething(ActivityListener listener) { | |
listener.showMessage(false, "DOWNLOADING"); | |
try { | |
Thread.sleep(5 * 1000); // simulate downloading something | |
} catch (InterruptedException e) { | |
listener.showMessage(true, e.getMessage()); | |
} | |
listener.showMessage(true, "DOWNLOADED, CLICK AGAIN!")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment