Skip to content

Instantly share code, notes, and snippets.

View diousk's full-sized avatar

David diousk

  • Taipei
View GitHub Profile
viewLifecycleOwner.lifecycleScope.launchWhenResumed {
context?.hideKeyboard(searchView)
awaitKeyboardHidden() // wait for keyboard dismissed
activity?.supportFragmentManager?.popBackStack()
}
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
}
}
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,
suspend fun View.awaitLayout() = suspendCancellableCoroutine<Unit>{
// use suspendCancellableCoroutine so that
// we can remove this listener when the job is cancelled
}
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
}
})
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
}
class DummyFragment @Inject constructor(
private val repo: AppRepo
) : DaggerFragment() {
// ...
}
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 MainActivity : DaggerAppCompatActivity() {
@Inject lateinit var fragmentFactory: FragmentFactory
override fun onCreate(savedInstanceState: Bundle?) {
supportFragmentManager.fragmentFactory = fragmentFactory
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
@Module
abstract class DummyBuilder {
@ContributesAndroidInjector(modules = [DummyModule::class])
abstract fun bindDummygFragment(): DummyFragment
// put binding of fragment at this layer(not DummyModule) for parent to inject
@Binds
@IntoMap
@FragmentKey(DummyFragment::class)
abstract fun bindDummyFragment(fragment: DummyFragment): Fragment