Skip to content

Instantly share code, notes, and snippets.

@e16din
Last active June 13, 2018 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save e16din/2bf66ef6ce58f04b536b2971de90195d to your computer and use it in GitHub Desktop.
Save e16din/2bf66ef6ce58f04b536b2971de90195d to your computer and use it in GitHub Desktop.
Закрывать диалог по клику вне области диалога (если setCanceledOnTouchOutside() не работает)
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import java.lang.ref.WeakReference
typealias OnCreateListener = (context: Context) -> Unit
class CancelableWrapperActivity : AppCompatActivity() {
companion object {
private var onCreateRef: WeakReference<OnCreateListener>? = null
fun start(context: Context, onCreate: OnCreateListener) {
onCreateRef = WeakReference(onCreate)
val intent = Intent(context, CancelableWrapperActivity::class.java)
context.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onCreateRef?.get()?.invoke(this)
val vContentContainer = findViewById<View>(android.R.id.content)
vContentContainer.setOnTouchListener { v, event ->
vContentContainer.setOnTouchListener(null)
finish()
true
}
}
override fun onStop() {
onCreateRef?.clear()
super.onStop()
}
override fun finish() {
super.finish()
overridePendingTransition(0, 0)
}
}
CancelableWrapperActivity.start(requireContext(), { context ->
val builder = AlertDialog.Builder(context)
// ...
builder.setCancelable(true)
val padding = resources.getDimension(R.dimen.feeds_theme_dialog_padding) * 2
val width = resources.displayMetrics.widthPixels - padding
val height = resources.displayMetrics.heightPixels - padding
val alertDialog = builder.create()
alertDialog.setCanceledOnTouchOutside(true)
alertDialog.show()
alertDialog.window.setLayout(width.toInt(), height.toInt())
alertDialog.window.setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL)
})
<activity
android:name=".CancelableWrapperActivity"
android:noHistory="true"
android:theme="@style/AppTheme.Translucent"/>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
...
</style>
<style name="AppTheme.Translucent">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">@null</item>
<item name="android:background">#00000000</item>
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment