Skip to content

Instantly share code, notes, and snippets.

View diousk's full-sized avatar

David diousk

  • Taipei
View GitHub Profile
public abstract class FragmentInjectActivity extends AppCompatActivity
implements HasAndroidInjector {
@Inject DispatchingAndroidInjector<Object> androidInjector;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
AndroidInjection.inject(this);
beforeOnCreate(); // <-- expose here for child to do things before onCreate
super.onCreate(savedInstanceState);
class DummyFragment @Inject constructor(
private val repo: AppRepo
) : DaggerFragment() {
// ...
}
class MainActivity : FragmentInjectActivity() {
@Inject lateinit var vmFactory: ViewModelProvider.Factory
private val viewModel by viewModels<MainViewModel> { vmFactory }
@Inject lateinit var fragmentFactory: FragmentFactory
override fun beforeOnCreate() {
supportFragmentManager.fragmentFactory = fragmentFactory
}
view.addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
override fun onLayoutChange(
view: View,
left: Int, top: Int, right: Int, bottom: Int,
oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int
) {
view.removeOnLayoutChangeListener(this)
// now you can do something on the view
}
})
suspend fun View.awaitLayout() = suspendCancellableCoroutine<Unit>{
// use suspendCancellableCoroutine so that
// we can remove this listener when the job is cancelled
}
suspend fun View.awaitLayout() = suspendCancellableCoroutine<Unit>{ cont ->
if (isLaidOut) {
// if view is laid out, just resume coroutine
cont.resume(Unit)
return@suspendCancellableCoroutine
}
val listener = object : View.OnLayoutChangeListener {
override fun onLayoutChange(
view: View,
left: Int,
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
viewLifecycleOwner.lifecycleScope.launchWhenCreated {
// before view laid out
requireView().awaitLayout() // coroutine suspended
// now view is laid out, we can get the size of view
}
}
viewLifecycleOwner.lifecycleScope.launchWhenResumed {
context?.hideKeyboard(searchView)
awaitKeyboardHidden() // wait for keyboard dismissed
activity?.supportFragmentManager?.popBackStack()
}
suspend fun Fragment.awaitKeyboardHidden() = suspendCancellableCoroutine<Unit> { cont ->
if (!KeyboardVisibilityEvent.isKeyboardVisible(activity)) {
cont.resume(Unit)
return@suspendCancellableCoroutine
}
var unRegistrar: Unregistrar? = null
unRegistrar = KeyboardVisibilityEvent.registerEventListener(activity) { open ->
if (!open) {
// keyboard dismissed, time to resume coroutine
@Module
abstract class ActivityBuilder {
 @PerActivity
 @ContributesAndroidInjector(modules = [SomeModule::class])
 abstract fun bindSomeActivity(): SomeActivity
}
@Module
abstract class SomeModule {
 @Provides