Triad


Source link: https://github.com/nhaarman/Triad

Triad

![In Progress](https://badge.waffle.io/nhaarman/triad.svg?label=in-progress&title=In Progress) ![Ready for Release](https://badge.waffle.io/nhaarman/triad.svg?label=next-release&title=Ready for Release)

Triad is a tiny Android library which enables use of the Model-View-Presenter pattern in an easy way. It uses custom Views to replace the dreaded Fragments, and introduces Presenter classes to separate business logic from view logic. Since the Presenters are plain Java objects, tests for these classes can run blazingly fast on a local JVM.

Triad is not a framework, but a tool that can help structure your ui logic in a clean and concise way.

Please note that Triad is still under development, and API's may will change. Although pretty stable, the need for simpler solutions and better API's may require changes in your code. Feel free to try it out and leave your feedback!

Setup

Add the following to your dependencies in your build.gradle file:

repositories {

jcenter() 
}
  dependencies {

// Pick one of the following:
compile 'com.nhaarman:triad:x.x.x'

// For Java
compile 'com.nhaarman:triad-appcompat-v7:x.x.x'

  // For Java and using the AppCompat-v7 library
compile 'com.nhaarman:triad-kotlin:x.x.x'

  // For Kotlin
compile 'com.nhaarman:triad-kotlin-appcompat-v7:x.x.x'
 // For Kotlin and using the AppCompat-v7 library 
}

How it works

We're gonna create a little counter app to get ourselves started. Whenever we touch a button a counter is incremented on screen:

Every screen in an application that uses Triad is represented by a Screen. A screen can consist of multiple components, each backed by a Presenter. In this case, we only have one presenter. The presenter communicates with a custom view ( CounterView) through an interface ( CounterContainer).

Screen

The CounterScreen class defines which layout to use, and instantiates the CounterPresenter class. The CounterView is automatically inflated and bound to the presenter.

public class CounterScreen extends Screen<ApplicationComponent> {

 @Override
protected int getLayoutResId() {

  return R.layout.view_counter;

}

 @Override
public Presenter<?, ?> createPresenter(final int viewId) {

  return new CounterPresenter();

}
 
}

View

The CounterView extends a ViewGroup, and reacts on user input of its children. The view notifies the presenter that something happened.

public class CounterView extends RelativeLayoutContainer<CounterPresenter, ActivityComponent> implements CounterContainer {

 @Bind(R.id.countertv)
protected TextView mCounterTV;
 public MyView(Context context, AttributeSet attrs) {

  super(context, attrs);

}

 public MyView(Context context, AttributeSet attrs, int defStyleAttr) {

  super(context, attrs, defStyleAttr);

}

 @Override
public void setCounterText(final String counterText) {

  mCounterTV.setText(counterText);

}

@OnClick(R.id.incrementbutton)
public void onIncrementButtonClicked() {

  getPresenter().onIncrementButtonClicked();

}
 
}

The xml layout of the view is defined below. The root of the layout is a CounterView, and the TextView and Button are nested inside the CounterView.

<?xml version="1.0" encoding="utf-8"?> <com.example.CounterView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
 <TextView
  android:id="@+id/countertv"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_centerInParent="true" />
 <Button
  android:id="@+id/incrementbutton"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_below="@id/countertv"
  android:layout_centerHorizontal="true"
  android:text="@string/increment" />  </com.example.CounterView>

Container

The CounterContainer acts as a separating layer between the presenter and view. This makes it possible to create different implementations of CounterView for different devices, such as phones or tablets.

interface CounterContainer extends Container {

 void setCounterText(String counterText) {
 
}

Presenter

Finally, the CounterPresenter handles any logic, and formats the data to display in the view. Presenters survive orientation changes, so our counter variable will not get lost on a configuration change.

class MyPresenter extends BasePresenter<MyContainer, ActivityComponent> {

 private int mCounter;
 CounterPresenter() {

  mCounter = 0;

}

 @Override
protected void onControlGained(@NonNull final CounterContainer container, @NonNull final ActivityComponent activityComponent) {

  container.setCounterText(formatCounterText());

}

 void onIncrementButtonClicked() {

  if (!container().isPresent()) {

 return;
  
}

mCounter++;
  container().get().setCounterText(formatCounterText());

}

 @NonNull
private String formatCounterText() {

  return String.valueOf(mCounter);

}
 
}

For more information, see the Wiki.

Flow

Navigating through screens is based on earlier versions of Square's Flow.

License

Copyright 2016 Niek Haarman  Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License. You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

Resources

Android dex file extractor,anti-bangcle.

Sharedsqlite is a simple thread-safe database with a single table with a key-value schema where you can save your primitive data types that suites nowhere else excluding the headache of messing around with committing and reading from the SharedPreferences.

A sample of the new percent support library.

SerializableParcelableGeneratorPlugin for IntelliJ IDEA & Android Studio to generator SerializableParcelable code.

MaterialDialogBottomSheet is a custom dialog implementation to use BottomSheet MaterialView feature of Lollipop in older versions

Pulls notifications from a remote JSON file and shows them in your app.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes