Replace cascade ifs with whens

This commit is contained in:
TacoTheDank 2020-06-08 20:21:48 -04:00
parent 50ee094889
commit 966bd2c7b5
39 changed files with 809 additions and 540 deletions

View File

@ -25,27 +25,39 @@ import java.util.*
@SuppressLint("RestrictedApi") @SuppressLint("RestrictedApi")
object LocaleHelperAccessor { object LocaleHelperAccessor {
fun forLanguageTag(str: String): Locale { fun forLanguageTag(str: String): Locale {
if (str.contains("-")) { when {
str.contains("-") -> {
val args = str.split("-").dropLastWhile { it.isEmpty() }.toTypedArray() val args = str.split("-").dropLastWhile { it.isEmpty() }.toTypedArray()
if (args.size > 2) { when {
args.size > 2 -> {
return Locale(args[0], args[1], args[2]) return Locale(args[0], args[1], args[2])
} else if (args.size > 1) { }
args.size > 1 -> {
return Locale(args[0], args[1]) return Locale(args[0], args[1])
} else if (args.size == 1) { }
args.size == 1 -> {
return Locale(args[0]) return Locale(args[0])
} }
} else if (str.contains("_")) { }
}
str.contains("_") -> {
val args = str.split("_").dropLastWhile { it.isEmpty() }.toTypedArray() val args = str.split("_").dropLastWhile { it.isEmpty() }.toTypedArray()
if (args.size > 2) { when {
args.size > 2 -> {
return Locale(args[0], args[1], args[2]) return Locale(args[0], args[1], args[2])
} else if (args.size > 1) { }
args.size > 1 -> {
return Locale(args[0], args[1]) return Locale(args[0], args[1])
} else if (args.size == 1) { }
args.size == 1 -> {
return Locale(args[0]) return Locale(args[0])
} }
} else { }
}
else -> {
return Locale(str) return Locale(str)
} }
}
throw IllegalArgumentException("Can not parse language tag: [$str]") throw IllegalArgumentException("Can not parse language tag: [$str]")
} }

View File

@ -35,21 +35,25 @@ object InternalActivityCreator {
activity.maxSortPosition = activity.minSortPosition activity.maxSortPosition = activity.minSortPosition
activity.createdAt = status.getCreatedAt() activity.createdAt = status.getCreatedAt()
if (status.getInReplyToUserId() == accountId) { when {
status.getInReplyToUserId() == accountId -> {
activity.action = Activity.Action.REPLY activity.action = Activity.Action.REPLY
activity.targetStatuses = arrayOf(status) activity.targetStatuses = arrayOf(status)
//TODO set target statuses (in reply to status) //TODO set target statuses (in reply to status)
activity.targetObjectStatuses = arrayOfNulls<Status>(0) activity.targetObjectStatuses = arrayOfNulls<Status>(0)
} else if (status.quotedStatus?.user?.id == accountId) { }
status.quotedStatus?.user?.id == accountId -> {
activity.action = Activity.Action.QUOTE activity.action = Activity.Action.QUOTE
activity.targetStatuses = arrayOf(status) activity.targetStatuses = arrayOf(status)
activity.targetObjectStatuses = arrayOfNulls<Status>(0) activity.targetObjectStatuses = arrayOfNulls<Status>(0)
} else { }
else -> {
activity.action = Activity.Action.MENTION activity.action = Activity.Action.MENTION
activity.targetUsers = arrayOfNulls<User>(0) activity.targetUsers = arrayOfNulls<User>(0)
activity.targetObjectStatuses = arrayOf(status) activity.targetObjectStatuses = arrayOf(status)
} }
}
activity.sourcesSize = 1 activity.sourcesSize = 1
activity.sources = arrayOf(status.getUser()) activity.sources = arrayOf(status.getUser())
return activity return activity

View File

@ -435,7 +435,10 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
val src = MediaPickerActivity.getMediaUris(data)?.takeIf(Array<Uri>::isNotEmpty) ?: val src = MediaPickerActivity.getMediaUris(data)?.takeIf(Array<Uri>::isNotEmpty) ?:
data.getParcelableExtra<Uri>(EXTRA_IMAGE_URI)?.let { arrayOf(it) } data.getParcelableExtra<Uri>(EXTRA_IMAGE_URI)?.let { arrayOf(it) }
if (src != null) { if (src != null) {
TaskStarter.execute(AddMediaTask(this, src, null, false, false)) TaskStarter.execute(AddMediaTask(this, src, null,
copySrc = false,
deleteSrc = false
))
} }
} }
} }
@ -1087,17 +1090,21 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
val action = intent.action val action = intent.action
val hasVisibility = intent.hasExtra(EXTRA_VISIBILITY) val hasVisibility = intent.hasExtra(EXTRA_VISIBILITY)
val hasAccountKeys: Boolean val hasAccountKeys: Boolean
if (intent.hasExtra(EXTRA_ACCOUNT_KEYS)) { when {
intent.hasExtra(EXTRA_ACCOUNT_KEYS) -> {
val accountKeys = intent.getTypedArrayExtra<UserKey>(EXTRA_ACCOUNT_KEYS) val accountKeys = intent.getTypedArrayExtra<UserKey>(EXTRA_ACCOUNT_KEYS)
accountsAdapter.selectedAccountKeys = accountKeys accountsAdapter.selectedAccountKeys = accountKeys
hasAccountKeys = true hasAccountKeys = true
} else if (intent.hasExtra(EXTRA_ACCOUNT_KEY)) { }
intent.hasExtra(EXTRA_ACCOUNT_KEY) -> {
val accountKey = intent.getParcelableExtra<UserKey>(EXTRA_ACCOUNT_KEY) val accountKey = intent.getParcelableExtra<UserKey>(EXTRA_ACCOUNT_KEY)
accountsAdapter.selectedAccountKeys = arrayOf(accountKey) accountsAdapter.selectedAccountKeys = arrayOf(accountKey)
hasAccountKeys = true hasAccountKeys = true
} else { }
else -> {
hasAccountKeys = false hasAccountKeys = false
} }
}
when (action) { when (action) {
Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE -> { Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE -> {
shouldSaveAccounts = false shouldSaveAccounts = false
@ -1105,7 +1112,10 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
val stream = intent.getStreamExtra() val stream = intent.getStreamExtra()
if (stream != null) { if (stream != null) {
val src = stream.toTypedArray() val src = stream.toTypedArray()
TaskStarter.execute(AddMediaTask(this, src, null, true, false)) TaskStarter.execute(AddMediaTask(this, src, null,
copySrc = true,
deleteSrc = false
))
} }
} }
else -> { else -> {
@ -1114,7 +1124,10 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
val data = intent.data val data = intent.data
if (data != null) { if (data != null) {
val src = arrayOf(data) val src = arrayOf(data)
TaskStarter.execute(AddMediaTask(this, src, null, true, false)) TaskStarter.execute(AddMediaTask(this, src, null,
copySrc = true,
deleteSrc = false
))
} }
} }
} }
@ -1820,7 +1833,10 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
}) })
editText.customSelectionActionModeCallback = this editText.customSelectionActionModeCallback = this
editText.imageInputListener = { contentInfo -> editText.imageInputListener = { contentInfo ->
val task = AddMediaTask(this, arrayOf(contentInfo.contentUri), null, true, false) val task = AddMediaTask(this, arrayOf(contentInfo.contentUri), null,
copySrc = true,
deleteSrc = false
)
task.callback = { task.callback = {
contentInfo.releasePermission() contentInfo.releasePermission()
} }
@ -2123,15 +2139,18 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
textView.spannable = ParcelableLocationUtils.getHumanReadableString(location, 3) textView.spannable = ParcelableLocationUtils.getHumanReadableString(location, 3)
textView.tag = location textView.tag = location
} else { } else {
val tag = textView.tag when (val tag = textView.tag) {
if (tag is Address) { is Address -> {
textView.spannable = tag.locality textView.spannable = tag.locality
} else if (tag is NoAddress) { }
is NoAddress -> {
textView.setText(R.string.label_location_your_coarse_location) textView.setText(R.string.label_location_your_coarse_location)
} else { }
else -> {
textView.setText(R.string.getting_location) textView.setText(R.string.getting_location)
} }
} }
}
} else { } else {
textView.setText(R.string.no_location) textView.setText(R.string.no_location)
} }

View File

@ -87,15 +87,19 @@ class FileSelectorActivity : BaseActivity(), FileSelectorDialogFragment.Callback
finish() finish()
return return
} }
if (checkAllSelfPermissionsGranted(AndroidPermissions.READ_EXTERNAL_STORAGE, AndroidPermissions.WRITE_EXTERNAL_STORAGE)) { when {
checkAllSelfPermissionsGranted(AndroidPermissions.READ_EXTERNAL_STORAGE, AndroidPermissions.WRITE_EXTERNAL_STORAGE) -> {
showPickFileDialog() showPickFileDialog()
} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) { }
Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN -> {
val permissions = arrayOf(AndroidPermissions.READ_EXTERNAL_STORAGE, AndroidPermissions.WRITE_EXTERNAL_STORAGE) val permissions = arrayOf(AndroidPermissions.READ_EXTERNAL_STORAGE, AndroidPermissions.WRITE_EXTERNAL_STORAGE)
ActivityCompat.requestPermissions(this, permissions, REQUEST_REQUEST_PERMISSIONS) ActivityCompat.requestPermissions(this, permissions, REQUEST_REQUEST_PERMISSIONS)
} else { }
else -> {
finishWithDeniedMessage() finishWithDeniedMessage()
} }
} }
}
private fun finishWithDeniedMessage() { private fun finishWithDeniedMessage() {
if (isFinishing) return if (isFinishing) return

View File

@ -428,24 +428,31 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
internal fun onSignInError(exception: Exception) { internal fun onSignInError(exception: Exception) {
DebugLog.w(LOGTAG, "Sign in error", exception) DebugLog.w(LOGTAG, "Sign in error", exception)
var errorReason: String? = null var errorReason: String? = null
if (exception is AuthenticityTokenException) { when (exception) {
is AuthenticityTokenException -> {
Toast.makeText(this, R.string.message_toast_wrong_api_key, Toast.LENGTH_SHORT).show() Toast.makeText(this, R.string.message_toast_wrong_api_key, Toast.LENGTH_SHORT).show()
errorReason = "wrong_api_key" errorReason = "wrong_api_key"
} else if (exception is WrongUserPassException) { }
is WrongUserPassException -> {
Toast.makeText(this, R.string.message_toast_wrong_username_password, Toast.LENGTH_SHORT).show() Toast.makeText(this, R.string.message_toast_wrong_username_password, Toast.LENGTH_SHORT).show()
errorReason = "wrong_username_password" errorReason = "wrong_username_password"
} else if (exception is SignInTask.WrongBasicCredentialException) { }
is SignInTask.WrongBasicCredentialException -> {
Toast.makeText(this, R.string.message_toast_wrong_username_password, Toast.LENGTH_SHORT).show() Toast.makeText(this, R.string.message_toast_wrong_username_password, Toast.LENGTH_SHORT).show()
errorReason = "wrong_username_password" errorReason = "wrong_username_password"
} else if (exception is SignInTask.WrongAPIURLFormatException) { }
is SignInTask.WrongAPIURLFormatException -> {
Toast.makeText(this, R.string.message_toast_wrong_api_key, Toast.LENGTH_SHORT).show() Toast.makeText(this, R.string.message_toast_wrong_api_key, Toast.LENGTH_SHORT).show()
errorReason = "wrong_api_key" errorReason = "wrong_api_key"
} else if (exception is LoginVerificationException) { }
is LoginVerificationException -> {
Toast.makeText(this, R.string.message_toast_login_verification_failed, Toast.LENGTH_SHORT).show() Toast.makeText(this, R.string.message_toast_login_verification_failed, Toast.LENGTH_SHORT).show()
errorReason = "login_verification_failed" errorReason = "login_verification_failed"
} else { }
else -> {
Toast.makeText(this, exception.getErrorMessage(this), Toast.LENGTH_SHORT).show() Toast.makeText(this, exception.getErrorMessage(this), Toast.LENGTH_SHORT).show()
} }
}
Analyzer.log(SignIn(false, credentialsType = apiConfig.credentialsType, Analyzer.log(SignIn(false, credentialsType = apiConfig.credentialsType,
errorReason = errorReason, accountType = apiConfig.type)) errorReason = errorReason, accountType = apiConfig.type))
} }

View File

@ -129,14 +129,18 @@ class UserSelectorActivity : BaseActivity(), OnItemClickListener, LoaderManager.
listContainer.visibility = View.VISIBLE listContainer.visibility = View.VISIBLE
adapter.setData(data, true) adapter.setData(data, true)
loader as CacheUserSearchLoader loader as CacheUserSearchLoader
if (data.isNotNullOrEmpty()) { when {
data.isNotNullOrEmpty() -> {
showList() showList()
} else if (loader.query.isEmpty()) { }
loader.query.isEmpty() -> {
showSearchHint() showSearchHint()
} else { }
else -> {
showNotFound() showNotFound()
} }
} }
}
private fun searchUser(accountKey: UserKey, query: String, fromCache: Boolean) { private fun searchUser(accountKey: UserKey, query: String, fromCache: Boolean) {
if (isEmpty(query)) { if (isEmpty(query)) {

View File

@ -80,14 +80,18 @@ class DummyItemAdapter(
} }
override fun getStatus(position: Int, raw: Boolean): ParcelableStatus { override fun getStatus(position: Int, raw: Boolean): ParcelableStatus {
if (adapter is ParcelableStatusesAdapter) { return when (adapter) {
return adapter.getStatus(position, raw) is ParcelableStatusesAdapter -> {
} else if (adapter is VariousItemsAdapter) { adapter.getStatus(position, raw)
return adapter.getItem(position) as ParcelableStatus }
} else if (adapter is ParcelableActivitiesAdapter) { is VariousItemsAdapter -> {
return adapter.getActivity(position).activityStatus!! adapter.getItem(position) as ParcelableStatus
}
is ParcelableActivitiesAdapter -> {
adapter.getActivity(position).activityStatus!!
}
else -> throw IndexOutOfBoundsException()
} }
throw IndexOutOfBoundsException()
} }
override fun getStatusCount(raw: Boolean) = 0 override fun getStatusCount(raw: Boolean) = 0

View File

@ -171,13 +171,16 @@ abstract class ParcelableStatusesAdapter(
override fun setData(data: List<ParcelableStatus>?): Boolean { override fun setData(data: List<ParcelableStatus>?): Boolean {
var changed = true var changed = true
if (data == null) { when (data) {
null -> {
displayPositions = null displayPositions = null
displayDataCount = 0 displayDataCount = 0
} else if (data is ObjectCursor) { }
is ObjectCursor -> {
displayPositions = null displayPositions = null
displayDataCount = data.size displayDataCount = data.size
} else { }
else -> {
var filteredCount = 0 var filteredCount = 0
displayPositions = IntArray(data.size).apply { displayPositions = IntArray(data.size).apply {
data.forEachIndexed { i, item -> data.forEachIndexed { i, item ->
@ -191,6 +194,7 @@ abstract class ParcelableStatusesAdapter(
displayDataCount = data.size - filteredCount displayDataCount = data.size - filteredCount
changed = this.data != data changed = this.data != data
} }
}
this.data = data this.data = data
this.infoCache = if (data != null) arrayOfNulls(data.size) else null this.infoCache = if (data != null) arrayOfNulls(data.size) else null
gapLoadingIds.clear() gapLoadingIds.clear()

View File

@ -43,17 +43,21 @@ fun View.getFrame(rect: Rect) {
@UiThread @UiThread
fun View.getFrameRelatedTo(rect: Rect, other: View? = null) { fun View.getFrameRelatedTo(rect: Rect, other: View? = null) {
this.getFrame(rect) this.getFrame(rect)
if (other == null) { when {
other == null -> {
offsetToRoot(this, rect) offsetToRoot(this, rect)
} else if (other === this) { }
other === this -> {
rect.offsetTo(0, 0) rect.offsetTo(0, 0)
} else if (other !== parent) { }
other !== parent -> {
offsetToRoot(this, rect) offsetToRoot(this, rect)
other.getFrame(tempRect) other.getFrame(tempRect)
offsetToRoot(other, tempRect) offsetToRoot(other, tempRect)
rect.offset(-tempRect.left, -tempRect.top) rect.offset(-tempRect.left, -tempRect.top)
} }
} }
}
fun View.getLocationOnScreen(rect: Rect) { fun View.getLocationOnScreen(rect: Rect) {
getLocationOnScreen(tempLocation) getLocationOnScreen(tempLocation)

View File

@ -29,15 +29,19 @@ fun Attachment.toParcelable(externalUrl: String?) : ParcelableMedia? {
val mimeType = mimetype ?: return null val mimeType = mimetype ?: return null
val result = ParcelableMedia() val result = ParcelableMedia()
if (mimeType.startsWith("image/")) { when {
mimeType.startsWith("image/") -> {
result.type = ParcelableMedia.Type.IMAGE result.type = ParcelableMedia.Type.IMAGE
} else if (mimeType.startsWith("video/")) { }
mimeType.startsWith("video/") -> {
result.type = ParcelableMedia.Type.VIDEO result.type = ParcelableMedia.Type.VIDEO
} else { }
else -> {
// https://github.com/TwidereProject/Twidere-Android/issues/729 // https://github.com/TwidereProject/Twidere-Android/issues/729
// Skip unsupported attachment // Skip unsupported attachment
return null return null
} }
}
result.width = width result.width = width
result.height = height result.height = height
result.url = externalUrl ?: url result.url = externalUrl ?: url

View File

@ -48,16 +48,21 @@ class APIEditorDialogFragment : BaseDialogFragment() {
val targetFragment = this.targetFragment val targetFragment = this.targetFragment
val parentFragment = this.parentFragment val parentFragment = this.parentFragment
val host = this.host val host = this.host
if (targetFragment is APIEditorCallback) { when {
targetFragment is APIEditorCallback -> {
targetFragment.onSaveAPIConfig(applyCustomAPIConfig()) targetFragment.onSaveAPIConfig(applyCustomAPIConfig())
} else if (parentFragment is APIEditorCallback) { }
parentFragment is APIEditorCallback -> {
parentFragment.onSaveAPIConfig(applyCustomAPIConfig()) parentFragment.onSaveAPIConfig(applyCustomAPIConfig())
} else if (host is APIEditorCallback) { }
host is APIEditorCallback -> {
host.onSaveAPIConfig(applyCustomAPIConfig()) host.onSaveAPIConfig(applyCustomAPIConfig())
} else { }
else -> {
kPreferences[defaultAPIConfigKey] = applyCustomAPIConfig() kPreferences[defaultAPIConfigKey] = applyCustomAPIConfig()
} }
} }
}
builder.setNegativeButton(android.R.string.cancel, null) builder.setNegativeButton(android.R.string.cancel, null)
val dialog = builder.create() val dialog = builder.create()

View File

@ -290,13 +290,17 @@ abstract class AbsStatusesFragment : AbsContentListRecyclerViewFragment<Parcelab
} else { } else {
firstVisibleItemPosition firstVisibleItemPosition
}.coerceInOr(statusRange, -1) }.coerceInOr(statusRange, -1)
lastReadId = if (lastReadPosition < 0) { lastReadId = when {
lastReadPosition < 0 -> {
-1 -1
} else if (useSortIdAsReadPosition) { }
useSortIdAsReadPosition -> {
adapter.getStatusSortId(lastReadPosition, false) adapter.getStatusSortId(lastReadPosition, false)
} else { }
else -> {
adapter.getStatusPositionKey(lastReadPosition) adapter.getStatusPositionKey(lastReadPosition)
} }
}
lastReadViewTop = layoutManager.findViewByPosition(lastReadPosition)?.top ?: 0 lastReadViewTop = layoutManager.findViewByPosition(lastReadPosition)?.top ?: 0
loadMore = statusRange.last in 0..lastVisibleItemPosition loadMore = statusRange.last in 0..lastVisibleItemPosition
} else if (rememberPosition) { } else if (rememberPosition) {
@ -623,19 +627,23 @@ abstract class AbsStatusesFragment : AbsContentListRecyclerViewFragment<Parcelab
} }
} }
R.id.favorite -> { R.id.favorite -> {
if (fragment.preferences[favoriteConfirmationKey]) { when {
fragment.preferences[favoriteConfirmationKey] -> {
fragment.executeAfterFragmentResumed { fragment.executeAfterFragmentResumed {
FavoriteConfirmDialogFragment.show(it.childFragmentManager, FavoriteConfirmDialogFragment.show(it.childFragmentManager,
status.account_key, status.id, status) status.account_key, status.id, status)
} }
} else if (status.is_favorite) { }
status.is_favorite -> {
fragment.twitterWrapper.destroyFavoriteAsync(status.account_key, status.id) fragment.twitterWrapper.destroyFavoriteAsync(status.account_key, status.id)
} else { }
else -> {
holder.playLikeAnimation(DefaultOnLikedListener(fragment.twitterWrapper, status)) holder.playLikeAnimation(DefaultOnLikedListener(fragment.twitterWrapper, status))
} }
} }
} }
} }
}
fun handleActionLongClick(fragment: Fragment, status: ParcelableStatus, itemId: Long, id: Int): Boolean { fun handleActionLongClick(fragment: Fragment, status: ParcelableStatus, itemId: Long, id: Int): Boolean {
when (id) { when (id) {
@ -721,17 +729,21 @@ abstract class AbsStatusesFragment : AbsContentListRecyclerViewFragment<Parcelab
return true return true
} }
ACTION_STATUS_FAVORITE -> { ACTION_STATUS_FAVORITE -> {
if (fragment.preferences[favoriteConfirmationKey]) { when {
fragment.preferences[favoriteConfirmationKey] -> {
fragment.executeAfterFragmentResumed { fragment.executeAfterFragmentResumed {
FavoriteConfirmDialogFragment.show(it.childFragmentManager, FavoriteConfirmDialogFragment.show(it.childFragmentManager,
status.account_key, status.id, status) status.account_key, status.id, status)
} }
} else if (status.is_favorite) { }
status.is_favorite -> {
fragment.twitterWrapper.destroyFavoriteAsync(status.account_key, status.id) fragment.twitterWrapper.destroyFavoriteAsync(status.account_key, status.id)
} else { }
else -> {
val holder = fragment.recyclerView.findViewHolderForLayoutPosition(position) as StatusViewHolder val holder = fragment.recyclerView.findViewHolderForLayoutPosition(position) as StatusViewHolder
holder.playLikeAnimation(DefaultOnLikedListener(fragment.twitterWrapper, status)) holder.playLikeAnimation(DefaultOnLikedListener(fragment.twitterWrapper, status))
} }
}
return true return true
} }
} }

View File

@ -532,13 +532,17 @@ class AccountsDashboardFragment : BaseFragment(), LoaderCallbacks<AccountsInfo>,
val width = if (bannerWidth > 0) bannerWidth else defWidth val width = if (bannerWidth > 0) bannerWidth else defWidth
val bannerView = accountProfileBanner.nextView as ImageView val bannerView = accountProfileBanner.nextView as ImageView
val user = account.user val user = account.user
val fallbackBanner = if (user.link_color != 0) { val fallbackBanner = when {
user.link_color != 0 -> {
ColorDrawable(user.link_color) ColorDrawable(user.link_color)
} else if (user.account_color != 0) { }
user.account_color != 0 -> {
ColorDrawable(user.account_color) ColorDrawable(user.account_color)
} else { }
else -> {
ColorDrawable(Chameleon.getOverrideTheme(requireActivity(), activity).colorPrimary) ColorDrawable(Chameleon.getOverrideTheme(requireActivity(), activity).colorPrimary)
} }
}
requestManager.loadProfileBanner(requireContext(), account.user, width).fallback(fallbackBanner) requestManager.loadProfileBanner(requireContext(), account.user, width).fallback(fallbackBanner)
.into(bannerView) .into(bannerView)

View File

@ -87,19 +87,23 @@ class AddStatusFilterDialogFragment : BaseDialogFragment() {
} }
val info = filterItems!![checkPositions.keyAt(i)] val info = filterItems!![checkPositions.keyAt(i)]
val value = info.value val value = info.value
if (value is ParcelableUserMention) { when {
value is ParcelableUserMention -> {
userKeys.add(value.key) userKeys.add(value.key)
userValues.add(ContentValuesCreator.createFilteredUser(value)) userValues.add(ContentValuesCreator.createFilteredUser(value))
} else if (value is UserItem) { }
value is UserItem -> {
userKeys.add(value.key) userKeys.add(value.key)
userValues.add(createFilteredUser(value)) userValues.add(createFilteredUser(value))
} else if (info.type == FilterItemInfo.FILTER_TYPE_KEYWORD) { }
info.type == FilterItemInfo.FILTER_TYPE_KEYWORD -> {
val keyword = ParseUtils.parseString(value) val keyword = ParseUtils.parseString(value)
keywords.add(keyword) keywords.add(keyword)
val values = ContentValues() val values = ContentValues()
values.put(Filters.Keywords.VALUE, "#$keyword") values.put(Filters.Keywords.VALUE, "#$keyword")
keywordValues.add(values) keywordValues.add(values)
} else if (info.type == FilterItemInfo.FILTER_TYPE_SOURCE) { }
info.type == FilterItemInfo.FILTER_TYPE_SOURCE -> {
val source = ParseUtils.parseString(value) val source = ParseUtils.parseString(value)
sources.add(source) sources.add(source)
val values = ContentValues() val values = ContentValues()
@ -107,6 +111,7 @@ class AddStatusFilterDialogFragment : BaseDialogFragment() {
sourceValues.add(values) sourceValues.add(values)
} }
} }
}
context?.contentResolver?.let { resolver -> context?.contentResolver?.let { resolver ->
ContentResolverUtils.bulkDelete(resolver, Filters.Users.CONTENT_URI, ContentResolverUtils.bulkDelete(resolver, Filters.Users.CONTENT_URI,
Filters.Users.USER_KEY, false, userKeys, null, null) Filters.Users.USER_KEY, false, userKeys, null, null)
@ -164,12 +169,15 @@ class AddStatusFilterDialogFragment : BaseDialogFragment() {
} }
private fun getName(manager: UserColorNameManager, value: Any, nameFirst: Boolean): String { private fun getName(manager: UserColorNameManager, value: Any, nameFirst: Boolean): String {
return if (value is ParcelableUserMention) { return when (value) {
is ParcelableUserMention -> {
manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst) manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
} else if (value is UserItem) { }
is UserItem -> {
manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst) manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
} else }
ParseUtils.parseString(value) else -> ParseUtils.parseString(value)
}
} }
internal data class FilterItemInfo( internal data class FilterItemInfo(

View File

@ -89,16 +89,21 @@ class ExtraFeaturesIntroductionDialogFragment : BaseDialogFragment() {
} }
private fun startActivityForResultOnTarget(intent: Intent) { private fun startActivityForResultOnTarget(intent: Intent) {
if (targetFragment != null) { when {
targetFragment != null -> {
targetFragment?.startActivityForResult(intent, targetRequestCode) targetFragment?.startActivityForResult(intent, targetRequestCode)
} else if (requestCode == 0) { }
requestCode == 0 -> {
startActivity(intent) startActivity(intent)
} else if (parentFragment != null) { }
parentFragment != null -> {
parentFragment?.startActivityForResult(intent, requestCode) parentFragment?.startActivityForResult(intent, requestCode)
} else { }
else -> {
activity?.startActivityForResult(intent, requestCode) activity?.startActivityForResult(intent, requestCode)
} }
} }
}
companion object { companion object {
const val EXTRA_FEATURE = "feature" const val EXTRA_FEATURE = "feature"

View File

@ -113,13 +113,17 @@ class GroupFragment : AbsToolbarTabPagesFragment(), LoaderCallbacks<SingleRespon
val twitter = MicroBlogAPIFactory.getInstance(context, accountKey) ?: val twitter = MicroBlogAPIFactory.getInstance(context, accountKey) ?:
throw MicroBlogException("No account") throw MicroBlogException("No account")
val group: Group val group: Group
group = if (groupId != null) { group = when {
groupId != null -> {
twitter.showGroup(groupId) twitter.showGroup(groupId)
} else if (groupName != null) { }
groupName != null -> {
twitter.showGroupByName(groupName) twitter.showGroupByName(groupName)
} else { }
else -> {
return SingleResponse() return SingleResponse()
} }
}
return SingleResponse.getInstance(ParcelableGroupUtils.from(group, accountKey, 0, return SingleResponse.getInstance(ParcelableGroupUtils.from(group, accountKey, 0,
group.isMember)) group.isMember))
} catch (e: MicroBlogException) { } catch (e: MicroBlogException) {

View File

@ -48,13 +48,17 @@ class SettingsDetailsFragment : BasePreferenceFragment(), OnSharedPreferenceChan
val args = arguments val args = arguments
val rawResId = args?.get(EXTRA_RESID) val rawResId = args?.get(EXTRA_RESID)
val resId: Int val resId: Int
resId = if (rawResId is Int) { resId = when (rawResId) {
is Int -> {
rawResId rawResId
} else if (rawResId is String) { }
is String -> {
Utils.getResId(activity, rawResId) Utils.getResId(activity, rawResId)
} else { }
else -> {
0 0
} }
}
if (resId != 0) { if (resId != 0) {
addPreferencesFromResource(resId) addPreferencesFromResource(resId)
} }
@ -81,13 +85,17 @@ class SettingsDetailsFragment : BasePreferenceFragment(), OnSharedPreferenceChan
val currentActivity = activity ?: return val currentActivity = activity ?: return
val extras = preference.extras val extras = preference.extras
if (extras != null) { if (extras != null) {
if (extras.containsKey(EXTRA_SHOULD_RESTART)) { when {
extras.containsKey(EXTRA_SHOULD_RESTART) -> {
SettingsActivity.setShouldRestart(currentActivity) SettingsActivity.setShouldRestart(currentActivity)
} else if (extras.containsKey(EXTRA_SHOULD_RECREATE)) { }
extras.containsKey(EXTRA_SHOULD_RECREATE) -> {
SettingsActivity.setShouldRecreate(currentActivity) SettingsActivity.setShouldRecreate(currentActivity)
} else if (extras.containsKey(EXTRA_SHOULD_TERMINATE)) { }
extras.containsKey(EXTRA_SHOULD_TERMINATE) -> {
SettingsActivity.setShouldTerminate(currentActivity) SettingsActivity.setShouldTerminate(currentActivity)
} }
}
if (extras.containsKey(EXTRA_RECREATE_ACTIVITY)) { if (extras.containsKey(EXTRA_RECREATE_ACTIVITY)) {
currentActivity.recreate() currentActivity.recreate()
} }

View File

@ -244,7 +244,8 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
override fun onLoadFinished(loader: Loader<SingleResponse<ParcelableUser>>, override fun onLoadFinished(loader: Loader<SingleResponse<ParcelableUser>>,
data: SingleResponse<ParcelableUser>) { data: SingleResponse<ParcelableUser>) {
val activity = activity ?: return val activity = activity ?: return
if (data.data != null) { when {
data.data != null -> {
val user = data.data val user = data.data
cardContent.visibility = View.VISIBLE cardContent.visibility = View.VISIBLE
errorContainer.visibility = View.GONE errorContainer.visibility = View.GONE
@ -260,13 +261,15 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
loaderManager.restartLoader(LOADER_ID_USER, args, this) loaderManager.restartLoader(LOADER_ID_USER, args, this)
} }
updateOptionsMenuVisibility() updateOptionsMenuVisibility()
} else if (user?.is_cache == true) { }
user?.is_cache == true -> {
cardContent.visibility = View.VISIBLE cardContent.visibility = View.VISIBLE
errorContainer.visibility = View.GONE errorContainer.visibility = View.GONE
progressContainer.visibility = View.GONE progressContainer.visibility = View.GONE
displayUser(user, account) displayUser(user, account)
updateOptionsMenuVisibility() updateOptionsMenuVisibility()
} else { }
else -> {
if (data.hasException()) { if (data.hasException()) {
errorText.text = data.exception?.getErrorMessage(activity) errorText.text = data.exception?.getErrorMessage(activity)
errorText.visibility = View.VISIBLE errorText.visibility = View.VISIBLE
@ -278,6 +281,7 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
updateOptionsMenuVisibility() updateOptionsMenuVisibility()
} }
} }
}
} }
@ -495,14 +499,18 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
listedContainer.visibility = if (user.listed_count < 0) View.GONE else View.VISIBLE listedContainer.visibility = if (user.listed_count < 0) View.GONE else View.VISIBLE
groupsContainer.visibility = if (user.groups_count < 0) View.GONE else View.VISIBLE groupsContainer.visibility = if (user.groups_count < 0) View.GONE else View.VISIBLE
if (user.color != 0) { when {
user.color != 0 -> {
setUiColor(user.color) setUiColor(user.color)
} else if (user.link_color != 0) { }
user.link_color != 0 -> {
setUiColor(user.link_color) setUiColor(user.link_color)
} else { }
else -> {
val theme = Chameleon.getOverrideTheme(activity, activity) val theme = Chameleon.getOverrideTheme(activity, activity)
setUiColor(theme.colorPrimary) setUiColor(theme.colorPrimary)
} }
}
val defWidth = resources.displayMetrics.widthPixels val defWidth = resources.displayMetrics.widthPixels
val width = if (bannerWidth > 0) bannerWidth else defWidth val width = if (bannerWidth > 0) bannerWidth else defWidth
context?.let { requestManager.loadProfileBanner(it, user, width).into(profileBanner) } context?.let { requestManager.loadProfileBanner(it, user, width).into(profileBanner) }
@ -1227,17 +1235,22 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
val userRelationship = relationship val userRelationship = relationship
val twitter = twitterWrapper val twitter = twitterWrapper
if (userRelationship == null) return if (userRelationship == null) return
if (userRelationship.blocking) { when {
userRelationship.blocking -> {
twitter.destroyBlockAsync(accountKey, user.key) twitter.destroyBlockAsync(accountKey, user.key)
} else if (userRelationship.blocked_by) { }
userRelationship.blocked_by -> {
CreateUserBlockDialogFragment.show(childFragmentManager, user) CreateUserBlockDialogFragment.show(childFragmentManager, user)
} else if (userRelationship.following) { }
userRelationship.following -> {
DestroyFriendshipDialogFragment.show(fragmentManager, user) DestroyFriendshipDialogFragment.show(fragmentManager, user)
} else { }
else -> {
twitter.createFriendshipAsync(accountKey, user.key, user.screen_name) twitter.createFriendshipAsync(accountKey, user.key, user.screen_name)
} }
} }
} }
}
R.id.profileImage -> { R.id.profileImage -> {
val url = user.originalProfileImage ?: return val url = user.originalProfileImage ?: return
val profileImage = ParcelableMediaUtils.image(url) val profileImage = ParcelableMediaUtils.image(url)

View File

@ -49,13 +49,17 @@ class GroupTimelineFragment : ParcelableStatusesFragment() {
val result = ArrayList<String>() val result = ArrayList<String>()
result.add(AUTHORITY_GROUP_TIMELINE) result.add(AUTHORITY_GROUP_TIMELINE)
result.add("account=$accountKey") result.add("account=$accountKey")
if (groupId != null) { when {
groupId != null -> {
result.add("group_id=$groupId") result.add("group_id=$groupId")
} else if (groupName != null) { }
groupName != null -> {
result.add("group_name=$groupName") result.add("group_name=$groupName")
} else { }
else -> {
return null return null
} }
}
return result.toTypedArray() return result.toTypedArray()
} }

View File

@ -46,13 +46,17 @@ class UserFavoritesFragment : ParcelableStatusesFragment() {
val result = ArrayList<String>() val result = ArrayList<String>()
result.add(AUTHORITY_USER_FAVORITES) result.add(AUTHORITY_USER_FAVORITES)
result.add("account=$accountKey") result.add("account=$accountKey")
if (userKey != null) { when {
userKey != null -> {
result.add("user_id=$userKey") result.add("user_id=$userKey")
} else if (screenName != null) { }
screenName != null -> {
result.add("screen_name=$screenName") result.add("screen_name=$screenName")
} else { }
else -> {
return null return null
} }
}
return result.toTypedArray() return result.toTypedArray()
} }
@ -65,13 +69,17 @@ class UserFavoritesFragment : ParcelableStatusesFragment() {
val userKey = arguments.getParcelable<UserKey>(EXTRA_USER_KEY) val userKey = arguments.getParcelable<UserKey>(EXTRA_USER_KEY)
val screenName = arguments.getString(EXTRA_SCREEN_NAME) val screenName = arguments.getString(EXTRA_SCREEN_NAME)
if (userKey != null) { when {
userKey != null -> {
sb.append(userKey) sb.append(userKey)
} else if (screenName != null) { }
screenName != null -> {
sb.append(screenName) sb.append(screenName)
} else { }
else -> {
return null return null
} }
}
return sb.toString() return sb.toString()
} }

View File

@ -49,18 +49,22 @@ class UserListTimelineFragment : ParcelableStatusesFragment() {
val result = ArrayList<String>() val result = ArrayList<String>()
result.add(TwidereConstants.AUTHORITY_USER_LIST_TIMELINE) result.add(TwidereConstants.AUTHORITY_USER_LIST_TIMELINE)
result.add("account=$accountKey") result.add("account=$accountKey")
if (listId != null) { when {
listId != null -> {
result.add("list_id=$listId") result.add("list_id=$listId")
} else if (listName != null) { }
listName != null -> {
if (userKey != null) { if (userKey != null) {
result.add("user_id=$userKey") result.add("user_id=$userKey")
} else if (screenName != null) { } else if (screenName != null) {
result.add("screen_name=$screenName") result.add("screen_name=$screenName")
} }
return null return null
} else { }
else -> {
return null return null
} }
}
return result.toTypedArray() return result.toTypedArray()
} }
@ -72,23 +76,31 @@ class UserListTimelineFragment : ParcelableStatusesFragment() {
if (tabPosition < 0) return null if (tabPosition < 0) return null
val listId = arguments.getString(EXTRA_LIST_ID) val listId = arguments.getString(EXTRA_LIST_ID)
val listName = arguments.getString(EXTRA_LIST_NAME) val listName = arguments.getString(EXTRA_LIST_NAME)
if (listId != null) { when {
listId != null -> {
sb.append(listId) sb.append(listId)
} else if (listName != null) { }
listName != null -> {
val userKey = arguments.getParcelable<UserKey?>(EXTRA_USER_KEY) val userKey = arguments.getParcelable<UserKey?>(EXTRA_USER_KEY)
val screenName = arguments.getString(EXTRA_SCREEN_NAME) val screenName = arguments.getString(EXTRA_SCREEN_NAME)
if (userKey != null) { when {
userKey != null -> {
sb.append(userKey) sb.append(userKey)
} else if (screenName != null) { }
screenName != null -> {
sb.append(screenName) sb.append(screenName)
} else { }
else -> {
return null return null
} }
}
sb.append('_') sb.append('_')
sb.append(listName) sb.append(listName)
} else { }
else -> {
return null return null
} }
}
return sb.toString() return sb.toString()
} }

View File

@ -61,13 +61,17 @@ class UserTimelineFragment : ParcelableStatusesFragment() {
val result = ArrayList<String>() val result = ArrayList<String>()
result.add(AUTHORITY_USER_TIMELINE) result.add(AUTHORITY_USER_TIMELINE)
result.add("account=$accountKey") result.add("account=$accountKey")
if (userKey != null) { when {
userKey != null -> {
result.add("user_id=$userKey") result.add("user_id=$userKey")
} else if (screenName != null) { }
screenName != null -> {
result.add("screen_name=$screenName") result.add("screen_name=$screenName")
} else { }
else -> {
return null return null
} }
}
(timelineFilter as? UserTimelineFilter)?.let { (timelineFilter as? UserTimelineFilter)?.let {
if (it.isIncludeReplies) { if (it.isIncludeReplies) {
result.add("include_replies") result.add("include_replies")
@ -87,13 +91,17 @@ class UserTimelineFragment : ParcelableStatusesFragment() {
val userKey = arguments.getParcelable<UserKey>(EXTRA_USER_KEY) val userKey = arguments.getParcelable<UserKey>(EXTRA_USER_KEY)
val screenName = arguments.getString(EXTRA_SCREEN_NAME) val screenName = arguments.getString(EXTRA_SCREEN_NAME)
if (userKey != null) { when {
userKey != null -> {
sb.append(userKey) sb.append(userKey)
} else if (screenName != null) { }
screenName != null -> {
sb.append(screenName) sb.append(screenName)
} else { }
else -> {
return null return null
} }
}
return sb.toString() return sb.toString()
} }

View File

@ -140,7 +140,8 @@ class UserTimelineLoader(
option.setExcludeReplies(!timelineFilter.isIncludeReplies) option.setExcludeReplies(!timelineFilter.isIncludeReplies)
option.setIncludeRetweets(timelineFilter.isIncludeRetweets) option.setIncludeRetweets(timelineFilter.isIncludeRetweets)
} }
if (userKey != null) { when {
userKey != null -> {
if (account.type == AccountType.STATUSNET && userKey.host != account.key.host if (account.type == AccountType.STATUSNET && userKey.host != account.key.host
&& profileUrl != null) { && profileUrl != null) {
try { try {
@ -150,12 +151,15 @@ class UserTimelineLoader(
} }
} }
return microBlog.getUserTimeline(userKey.id, paging, option) return microBlog.getUserTimeline(userKey.id, paging, option)
} else if (screenName != null) { }
screenName != null -> {
return microBlog.getUserTimelineByScreenName(screenName, paging, option) return microBlog.getUserTimelineByScreenName(screenName, paging, option)
} else { }
else -> {
throw MicroBlogException("Invalid user") throw MicroBlogException("Invalid user")
} }
} }
}
@Throws(IOException::class) @Throws(IOException::class)
private fun showStatusNetExternalTimeline(profileUrl: String, paging: Paging): List<Status> { private fun showStatusNetExternalTimeline(profileUrl: String, paging: Paging): List<Status> {

View File

@ -229,10 +229,12 @@ class ActivityTitleSummaryMessage private constructor(val icon: Int, val color:
nameFirst)) nameFirst))
firstDisplayName.setSpan(StyleSpan(Typeface.BOLD), 0, firstDisplayName.length, firstDisplayName.setSpan(StyleSpan(Typeface.BOLD), 0, firstDisplayName.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
if (sources.size == 1) { when (sources.size) {
1 -> {
val format = resources.getString(stringRes) val format = resources.getString(stringRes)
return SpanFormatter.format(format, firstDisplayName) return SpanFormatter.format(format, firstDisplayName)
} else if (sources.size == 2) { }
2 -> {
val format = resources.getString(stringResMulti) val format = resources.getString(stringResMulti)
val secondDisplayName = SpannableString(manager.getDisplayName(sources[1], val secondDisplayName = SpannableString(manager.getDisplayName(sources[1],
nameFirst)) nameFirst))
@ -240,7 +242,8 @@ class ActivityTitleSummaryMessage private constructor(val icon: Int, val color:
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
return SpanFormatter.format(format, firstDisplayName, return SpanFormatter.format(format, firstDisplayName,
secondDisplayName) secondDisplayName)
} else { }
else -> {
val othersCount = sources.size - 1 val othersCount = sources.size - 1
val nOthers = resources.getQuantityString(R.plurals.N_others, othersCount, othersCount) val nOthers = resources.getQuantityString(R.plurals.N_others, othersCount, othersCount)
val format = resources.getString(stringResMulti) val format = resources.getString(stringResMulti)
@ -249,3 +252,4 @@ class ActivityTitleSummaryMessage private constructor(val icon: Int, val color:
} }
} }
} }
}

View File

@ -414,16 +414,20 @@ class TwidereDataProvider : ContentProvider(), LazyLoadCallback {
} }
else -> { else -> {
val conflictAlgorithm = getConflictAlgorithm(tableId) val conflictAlgorithm = getConflictAlgorithm(tableId)
rowId = if (conflictAlgorithm != SQLiteDatabase.CONFLICT_NONE) { rowId = when {
conflictAlgorithm != SQLiteDatabase.CONFLICT_NONE -> {
databaseWrapper.insertWithOnConflict(table, null, values, databaseWrapper.insertWithOnConflict(table, null, values,
conflictAlgorithm) conflictAlgorithm)
} else if (table != null) { }
table != null -> {
databaseWrapper.insert(table, null, values) databaseWrapper.insert(table, null, values)
} else { }
else -> {
return null return null
} }
} }
} }
}
onDatabaseUpdated(tableId, uri) onDatabaseUpdated(tableId, uri)
onNewItemsInserted(uri, tableId, arrayOf(values)) onNewItemsInserted(uri, tableId, arrayOf(values))
return uri.withAppendedPath(rowId.toString()) return uri.withAppendedPath(rowId.toString())

View File

@ -119,14 +119,18 @@ class HtmlBuilder(
} }
private fun appendSource(builder: StringBuilder, start: Int, end: Int, escapeSource: Boolean, sourceEscaped: Boolean) { private fun appendSource(builder: StringBuilder, start: Int, end: Int, escapeSource: Boolean, sourceEscaped: Boolean) {
if (sourceEscaped == escapeSource) { when {
sourceEscaped == escapeSource -> {
builder.append(source.substring(start, end), escapeSource, sourceEscaped) builder.append(source.substring(start, end), escapeSource, sourceEscaped)
} else if (escapeSource) { }
escapeSource -> {
builder.append(HtmlEscapeHelper.escape(source.substring(start, end)), true, sourceEscaped) builder.append(HtmlEscapeHelper.escape(source.substring(start, end)), true, sourceEscaped)
} else { }
else -> {
builder.append(HtmlEscapeHelper.unescape(source.substring(start, end)), false, sourceEscaped) builder.append(HtmlEscapeHelper.unescape(source.substring(start, end)), false, sourceEscaped)
} }
} }
}
private fun escapeSource(): String { private fun escapeSource(): String {
val source = this.source.substring(0, this.source.length()) val source = this.source.substring(0, this.source.length())
@ -166,14 +170,18 @@ class HtmlBuilder(
companion object { companion object {
private fun StringBuilder.append(text: String, escapeText: Boolean, textEscaped: Boolean) { private fun StringBuilder.append(text: String, escapeText: Boolean, textEscaped: Boolean) {
if (textEscaped == escapeText) { when {
textEscaped == escapeText -> {
append(text) append(text)
} else if (escapeText) { }
escapeText -> {
append(HtmlEscapeHelper.escape(text)) append(HtmlEscapeHelper.escape(text))
} else { }
else -> {
append(HtmlEscapeHelper.unescape(text)) append(HtmlEscapeHelper.unescape(text))
} }
} }
} }
}
} }

View File

@ -125,13 +125,17 @@ object MenuUtils {
val favoriteHighlight = ContextCompat.getColor(context, R.color.highlight_favorite) val favoriteHighlight = ContextCompat.getColor(context, R.color.highlight_favorite)
val likeHighlight = ContextCompat.getColor(context, R.color.highlight_like) val likeHighlight = ContextCompat.getColor(context, R.color.highlight_like)
val isMyRetweet: Boolean = val isMyRetweet: Boolean =
if (RetweetStatusTask.isCreatingRetweet(status.account_key, status.id)) { when {
RetweetStatusTask.isCreatingRetweet(status.account_key, status.id) -> {
true true
} else if (twitter.isDestroyingStatus(status.account_key, status.id)) { }
twitter.isDestroyingStatus(status.account_key, status.id) -> {
false false
} else { }
else -> {
status.retweeted || Utils.isMyRetweet(status) status.retweeted || Utils.isMyRetweet(status)
} }
}
val isMyStatus = Utils.isMyStatus(status) val isMyStatus = Utils.isMyStatus(status)
menu.setItemAvailability(R.id.delete, isMyStatus) menu.setItemAvailability(R.id.delete, isMyStatus)
if (isMyStatus) { if (isMyStatus) {
@ -165,13 +169,17 @@ object MenuUtils {
val favorite = menu.findItem(R.id.favorite) val favorite = menu.findItem(R.id.favorite)
if (favorite != null) { if (favorite != null) {
val isFavorite: Boolean = val isFavorite: Boolean =
if (CreateFavoriteTask.isCreatingFavorite(status.account_key, status.id)) { when {
CreateFavoriteTask.isCreatingFavorite(status.account_key, status.id) -> {
true true
} else if (DestroyFavoriteTask.isDestroyingFavorite(status.account_key, status.id)) { }
DestroyFavoriteTask.isDestroyingFavorite(status.account_key, status.id) -> {
false false
} else { }
else -> {
status.is_favorite status.is_favorite
} }
}
val provider = MenuItemCompat.getActionProvider(favorite) val provider = MenuItemCompat.getActionProvider(favorite)
val useStar = preferences[iWantMyStarsBackKey] val useStar = preferences[iWantMyStarsBackKey]
if (provider is FavoriteItemProvider) { if (provider is FavoriteItemProvider) {
@ -205,21 +213,26 @@ object MenuUtils {
INTENT_ACTION_EXTENSION_OPEN_STATUS, EXTRA_STATUS, EXTRA_STATUS_JSON, status) INTENT_ACTION_EXTENSION_OPEN_STATUS, EXTRA_STATUS, EXTRA_STATUS_JSON, status)
val shareItem = menu.findItem(R.id.share) val shareItem = menu.findItem(R.id.share)
val shareProvider = MenuItemCompat.getActionProvider(shareItem) val shareProvider = MenuItemCompat.getActionProvider(shareItem)
if (shareProvider is SupportStatusShareProvider) { when {
shareProvider is SupportStatusShareProvider -> {
shareProvider.status = status shareProvider.status = status
} else if (shareProvider is ShareActionProvider) { }
shareProvider is ShareActionProvider -> {
val shareIntent = Utils.createStatusShareIntent(context, status) val shareIntent = Utils.createStatusShareIntent(context, status)
shareProvider.setShareIntent(shareIntent) shareProvider.setShareIntent(shareIntent)
} else if (shareItem.hasSubMenu()) { }
shareItem.hasSubMenu() -> {
val shareSubMenu = shareItem.subMenu val shareSubMenu = shareItem.subMenu
val shareIntent = Utils.createStatusShareIntent(context, status) val shareIntent = Utils.createStatusShareIntent(context, status)
shareSubMenu.removeGroup(MENU_GROUP_STATUS_SHARE) shareSubMenu.removeGroup(MENU_GROUP_STATUS_SHARE)
addIntentToMenu(context, shareSubMenu, shareIntent, MENU_GROUP_STATUS_SHARE) addIntentToMenu(context, shareSubMenu, shareIntent, MENU_GROUP_STATUS_SHARE)
} else { }
else -> {
val shareIntent = Utils.createStatusShareIntent(context, status) val shareIntent = Utils.createStatusShareIntent(context, status)
val chooserIntent = Intent.createChooser(shareIntent, context.getString(R.string.share_status)) val chooserIntent = Intent.createChooser(shareIntent, context.getString(R.string.share_status))
shareItem.intent = chooserIntent shareItem.intent = chooserIntent
} }
}
} }
@ -233,21 +246,25 @@ object MenuUtils {
} }
} }
R.id.retweet -> { R.id.retweet -> {
if (fragment is BaseFragment) { when {
fragment is BaseFragment -> {
fragment.executeAfterFragmentResumed { fragment.executeAfterFragmentResumed {
RetweetQuoteDialogFragment.show(it.childFragmentManager, status.account_key, RetweetQuoteDialogFragment.show(it.childFragmentManager, status.account_key,
status.id, status) status.id, status)
} }
} else if (context is BaseActivity) { }
context is BaseActivity -> {
context.executeAfterFragmentResumed { context.executeAfterFragmentResumed {
RetweetQuoteDialogFragment.show(it.supportFragmentManager, status.account_key, RetweetQuoteDialogFragment.show(it.supportFragmentManager, status.account_key,
status.id, status) status.id, status)
} }
} else { }
else -> {
RetweetQuoteDialogFragment.show(fm, status.account_key, RetweetQuoteDialogFragment.show(fm, status.account_key,
status.id, status) status.id, status)
} }
} }
}
R.id.quote -> { R.id.quote -> {
val intent = Intent(INTENT_ACTION_QUOTE) val intent = Intent(INTENT_ACTION_QUOTE)
intent.putExtra(EXTRA_STATUS, status) intent.putExtra(EXTRA_STATUS, status)
@ -260,20 +277,24 @@ object MenuUtils {
} }
R.id.favorite -> { R.id.favorite -> {
if (preferences[favoriteConfirmationKey]) { if (preferences[favoriteConfirmationKey]) {
if (fragment is BaseFragment) { when {
fragment is BaseFragment -> {
fragment.executeAfterFragmentResumed { fragment.executeAfterFragmentResumed {
FavoriteConfirmDialogFragment.show(it.childFragmentManager, FavoriteConfirmDialogFragment.show(it.childFragmentManager,
status.account_key, status.id, status) status.account_key, status.id, status)
} }
} else if (context is BaseActivity) { }
context is BaseActivity -> {
context.executeAfterFragmentResumed { context.executeAfterFragmentResumed {
FavoriteConfirmDialogFragment.show(it.supportFragmentManager, FavoriteConfirmDialogFragment.show(it.supportFragmentManager,
status.account_key, status.id, status) status.account_key, status.id, status)
} }
} else { }
else -> {
FavoriteConfirmDialogFragment.show(fm, status.account_key, status.id, FavoriteConfirmDialogFragment.show(fm, status.account_key, status.id,
status) status)
} }
}
} else if (status.is_favorite) { } else if (status.is_favorite) {
twitter.destroyFavoriteAsync(status.account_key, status.id) twitter.destroyFavoriteAsync(status.account_key, status.id)
} else { } else {

View File

@ -116,14 +116,18 @@ object ThemeUtils {
fun getCardBackgroundColor(context: Context, backgroundOption: String, themeAlpha: Int): Int { fun getCardBackgroundColor(context: Context, backgroundOption: String, themeAlpha: Int): Int {
val color = getColorFromAttribute(context, R.attr.cardItemBackgroundColor) val color = getColorFromAttribute(context, R.attr.cardItemBackgroundColor)
return if (isTransparentBackground(backgroundOption)) { return when {
isTransparentBackground(backgroundOption) -> {
ColorUtils.setAlphaComponent(color, themeAlpha) ColorUtils.setAlphaComponent(color, themeAlpha)
} else if (isSolidBackground(backgroundOption)) { }
isSolidBackground(backgroundOption) -> {
TwidereColorUtils.getContrastYIQ(color, Color.WHITE, Color.BLACK) TwidereColorUtils.getContrastYIQ(color, Color.WHITE, Color.BLACK)
} else { }
else -> {
color color
} }
} }
}
fun isLightColor(color: Int): Boolean { fun isLightColor(color: Int): Boolean {
return ChameleonUtils.isColorLight(color) return ChameleonUtils.isColorLight(color)
@ -163,17 +167,22 @@ object ThemeUtils {
} }
fun applyWindowBackground(context: Context, window: Window, backgroundOption: String, alpha: Int) { fun applyWindowBackground(context: Context, window: Window, backgroundOption: String, alpha: Int) {
if (isWindowFloating(context)) { when {
isWindowFloating(context) -> {
window.setBackgroundDrawable(getWindowBackground(context)) window.setBackgroundDrawable(getWindowBackground(context))
} else if (VALUE_THEME_BACKGROUND_TRANSPARENT == backgroundOption) { }
VALUE_THEME_BACKGROUND_TRANSPARENT == backgroundOption -> {
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER) window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER)
window.setBackgroundDrawable(getWindowBackgroundFromThemeApplyAlpha(context, alpha)) window.setBackgroundDrawable(getWindowBackgroundFromThemeApplyAlpha(context, alpha))
} else if (VALUE_THEME_BACKGROUND_SOLID == backgroundOption) { }
VALUE_THEME_BACKGROUND_SOLID == backgroundOption -> {
window.setBackgroundDrawable(ColorDrawable(if (isLightTheme(context)) Color.WHITE else Color.BLACK)) window.setBackgroundDrawable(ColorDrawable(if (isLightTheme(context)) Color.WHITE else Color.BLACK))
} else { }
else -> {
window.setBackgroundDrawable(getWindowBackground(context)) window.setBackgroundDrawable(getWindowBackground(context))
} }
} }
}
fun wrapMenuIcon(menu: Menu, itemColor: Int, subItemColor: Int, vararg excludeGroups: Int) { fun wrapMenuIcon(menu: Menu, itemColor: Int, subItemColor: Int, vararg excludeGroups: Int) {

View File

@ -160,12 +160,15 @@ object Utils {
fun getAccountKeys(context: Context, args: Bundle?): Array<UserKey>? { fun getAccountKeys(context: Context, args: Bundle?): Array<UserKey>? {
if (args == null) return null if (args == null) return null
if (args.containsKey(EXTRA_ACCOUNT_KEYS)) { when {
args.containsKey(EXTRA_ACCOUNT_KEYS) -> {
return args.getNullableTypedArray(EXTRA_ACCOUNT_KEYS) return args.getNullableTypedArray(EXTRA_ACCOUNT_KEYS)
} else if (args.containsKey(EXTRA_ACCOUNT_KEY)) { }
args.containsKey(EXTRA_ACCOUNT_KEY) -> {
val accountKey = args.getParcelable<UserKey>(EXTRA_ACCOUNT_KEY) ?: return emptyArray() val accountKey = args.getParcelable<UserKey>(EXTRA_ACCOUNT_KEY) ?: return emptyArray()
return arrayOf(accountKey) return arrayOf(accountKey)
} else if (args.containsKey(EXTRA_ACCOUNT_ID)) { }
args.containsKey(EXTRA_ACCOUNT_ID) -> {
val accountId = args.get(EXTRA_ACCOUNT_ID).toString() val accountId = args.get(EXTRA_ACCOUNT_ID).toString()
try { try {
if (java.lang.Long.parseLong(accountId) <= 0) return null if (java.lang.Long.parseLong(accountId) <= 0) return null
@ -178,7 +181,8 @@ object Utils {
if (accountKey == null) return arrayOf(UserKey(accountId, null)) if (accountKey == null) return arrayOf(UserKey(accountId, null))
return arrayOf(accountKey) return arrayOf(accountKey)
} }
return null else -> return null
}
} }
fun getAccountKey(context: Context, args: Bundle?): UserKey? { fun getAccountKey(context: Context, args: Bundle?): UserKey? {
@ -456,13 +460,17 @@ object Utils {
} }
fun getInsetsTopWithoutActionBarHeight(context: Context, top: Int): Int { fun getInsetsTopWithoutActionBarHeight(context: Context, top: Int): Int {
val actionBarHeight: Int = if (context is AppCompatActivity) { val actionBarHeight: Int = when (context) {
is AppCompatActivity -> {
getActionBarHeight(context.supportActionBar) getActionBarHeight(context.supportActionBar)
} else if (context is Activity) { }
is Activity -> {
getActionBarHeight(context.actionBar) getActionBarHeight(context.actionBar)
} else { }
else -> {
return top return top
} }
}
if (actionBarHeight > top) { if (actionBarHeight > top) {
return top return top
} }

View File

@ -35,13 +35,17 @@ import java.io.IOException
object TwidereExceptionFactory : ExceptionFactory<MicroBlogException> { object TwidereExceptionFactory : ExceptionFactory<MicroBlogException> {
override fun newException(cause: Throwable?, request: HttpRequest?, response: HttpResponse?): MicroBlogException { override fun newException(cause: Throwable?, request: HttpRequest?, response: HttpResponse?): MicroBlogException {
val te = if (cause != null) { val te = when {
cause != null -> {
MicroBlogException(cause) MicroBlogException(cause)
} else if (response != null) { }
response != null -> {
parseTwitterException(response) parseTwitterException(response)
} else { }
else -> {
MicroBlogException() MicroBlogException()
} }
}
te.httpRequest = request te.httpRequest = request
te.httpResponse = response te.httpResponse = response
return te return te

View File

@ -123,17 +123,21 @@ class ContentNotificationManager(
val displayName = userColorNameManager.getDisplayName(userCursor.getString(userIndices[Statuses.USER_KEY]), val displayName = userColorNameManager.getDisplayName(userCursor.getString(userIndices[Statuses.USER_KEY]),
userCursor.getString(userIndices[Statuses.USER_NAME]), userCursor.getString(userIndices[Statuses.USER_SCREEN_NAME]), userCursor.getString(userIndices[Statuses.USER_NAME]), userCursor.getString(userIndices[Statuses.USER_SCREEN_NAME]),
nameFirst) nameFirst)
notificationContent = if (usersCount == 1) { notificationContent = when (usersCount) {
1 -> {
context.getString(R.string.from_name, displayName) context.getString(R.string.from_name, displayName)
} else if (usersCount == 2) { }
2 -> {
userCursor.moveToPosition(1) userCursor.moveToPosition(1)
val othersName = userColorNameManager.getDisplayName(userCursor.getString(userIndices[Statuses.USER_KEY]), val othersName = userColorNameManager.getDisplayName(userCursor.getString(userIndices[Statuses.USER_KEY]),
userCursor.getString(userIndices[Statuses.USER_NAME]), userCursor.getString(userIndices[Statuses.USER_SCREEN_NAME]), userCursor.getString(userIndices[Statuses.USER_NAME]), userCursor.getString(userIndices[Statuses.USER_SCREEN_NAME]),
nameFirst) nameFirst)
resources.getString(R.string.from_name_and_name, displayName, othersName) resources.getString(R.string.from_name_and_name, displayName, othersName)
} else { }
else -> {
resources.getString(R.string.from_name_and_N_others, displayName, usersCount - 1) resources.getString(R.string.from_name_and_N_others, displayName, usersCount - 1)
} }
}
// Setup notification // Setup notification
val builder = NotificationChannelSpec.contentUpdates.accountNotificationBuilder(context, val builder = NotificationChannelSpec.contentUpdates.accountNotificationBuilder(context,

View File

@ -72,22 +72,27 @@ abstract class FileBasedDraftsSyncAction<RemoteFileInfo>(val context: Context) :
remoteDrafts.forEach { remoteDraft -> remoteDrafts.forEach { remoteDraft ->
val localDraft = localDrafts.find { it.filename == remoteDraft.draftFileName } val localDraft = localDrafts.find { it.filename == remoteDraft.draftFileName }
if (remoteDraft.draftFileName.substringBefore(".eml") in localRemovedIds) { when {
remoteDraft.draftFileName.substringBefore(".eml") in localRemovedIds -> {
// Local removed, remove remote // Local removed, remove remote
removeRemoteInfoList.add(remoteDraft) removeRemoteInfoList.add(remoteDraft)
} else if (localDraft == null) { }
localDraft == null -> {
// Local doesn't exist, download remote // Local doesn't exist, download remote
downloadRemoteInfoList.add(remoteDraft) downloadRemoteInfoList.add(remoteDraft)
} else if (remoteDraft.draftTimestamp - localDraft.timestamp > 1000) { }
remoteDraft.draftTimestamp - localDraft.timestamp > 1000 -> {
// Local is older, update from remote // Local is older, update from remote
localDraft.remote_extras = remoteDraft.draftRemoteExtras localDraft.remote_extras = remoteDraft.draftRemoteExtras
updateLocalInfoList[localDraft._id] = remoteDraft updateLocalInfoList[localDraft._id] = remoteDraft
} else if (localDraft.timestamp - remoteDraft.draftTimestamp > 1000) { }
localDraft.timestamp - remoteDraft.draftTimestamp > 1000 -> {
// Local is newer, upload local // Local is newer, upload local
localDraft.remote_extras = remoteDraft.draftRemoteExtras localDraft.remote_extras = remoteDraft.draftRemoteExtras
uploadLocalList.add(localDraft) uploadLocalList.add(localDraft)
} }
} }
}
// Deal with local drafts that remote doesn't have // Deal with local drafts that remote doesn't have
localDrafts.filterTo(uploadLocalList) { localDraft -> localDrafts.filterTo(uploadLocalList) { localDraft ->

View File

@ -53,14 +53,18 @@ abstract class TwitterCardViewFactory {
private fun createCardFragment(status: ParcelableStatus): ContainerView.ViewController? { private fun createCardFragment(status: ParcelableStatus): ContainerView.ViewController? {
val card = status.card val card = status.card
if (card?.name == null) return null if (card?.name == null) return null
if (TwitterCardUtils.CARD_NAME_PLAYER == card.name) { return when {
return createGenericPlayerFragment(card) TwitterCardUtils.CARD_NAME_PLAYER == card.name -> {
} else if (TwitterCardUtils.CARD_NAME_AUDIO == card.name) { createGenericPlayerFragment(card)
return createGenericPlayerFragment(card) }
} else if (TwitterCardUtils.isPoll(card)) { TwitterCardUtils.CARD_NAME_AUDIO == card.name -> {
return createCardPollFragment(status) createGenericPlayerFragment(card)
}
TwitterCardUtils.isPoll(card) -> {
createCardPollFragment(status)
}
else -> null
} }
return null
} }

View File

@ -97,13 +97,17 @@ class ActionIconThemedTextView(
for (d in TextViewSupport.getCompoundDrawablesRelative(this)) { for (d in TextViewSupport.getCompoundDrawablesRelative(this)) {
if (d == null) continue if (d == null) continue
d.mutate() d.mutate()
val color: Int = if (isActivated) { val color: Int = when {
isActivated -> {
activatedColor activatedColor
} else if (isEnabled) { }
isEnabled -> {
defaultColor defaultColor
} else { }
else -> {
disabledColor disabledColor
} }
}
if (iconWidth > 0 && iconHeight > 0) { if (iconWidth > 0 && iconHeight > 0) {
val top = (d.intrinsicHeight - iconHeight) / 2 val top = (d.intrinsicHeight - iconHeight) / 2

View File

@ -65,17 +65,21 @@ class CardMediaContainer(context: Context, attrs: AttributeSet? = null) : ViewGr
val k = imageRes.size val k = imageRes.size
for (i in 0 until childCount) { for (i in 0 until childCount) {
val child = getChildAt(i) val child = getChildAt(i)
if (child !is ImageView) { when {
child !is ImageView -> {
child.visibility = View.GONE child.visibility = View.GONE
} else if (i < k) { }
i < k -> {
child.setImageResource(imageRes[i]) child.setImageResource(imageRes[i])
child.visibility = View.VISIBLE child.visibility = View.VISIBLE
} else { }
else -> {
child.setImageDrawable(null) child.setImageDrawable(null)
child.visibility = View.GONE child.visibility = View.GONE
} }
} }
} }
}
fun displayMedia(requestManager: RequestManager, media: Array<ParcelableMedia>?, accountKey: UserKey? = null, fun displayMedia(requestManager: RequestManager, media: Array<ParcelableMedia>?, accountKey: UserKey? = null,
extraId: Long = -1, withCredentials: Boolean = false, extraId: Long = -1, withCredentials: Boolean = false,
@ -159,15 +163,19 @@ class CardMediaContainer(context: Context, attrs: AttributeSet? = null) : ViewGr
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
val childCount = rebuildChildInfo() val childCount = rebuildChildInfo()
if (childCount > 0) { if (childCount > 0) {
if (childCount == 1) { when (childCount) {
1 -> {
layout1Media(childIndices) layout1Media(childIndices)
} else if (childCount == 3) { }
3 -> {
layout3Media(horizontalSpacing, verticalSpacing, childIndices) layout3Media(horizontalSpacing, verticalSpacing, childIndices)
} else { }
else -> {
layoutGridMedia(childCount, 2, horizontalSpacing, verticalSpacing, childIndices) layoutGridMedia(childCount, 2, horizontalSpacing, verticalSpacing, childIndices)
} }
} }
} }
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val measuredWidth = View.resolveSize(suggestedMinimumWidth, widthMeasureSpec) val measuredWidth = View.resolveSize(suggestedMinimumWidth, widthMeasureSpec)
@ -182,17 +190,22 @@ class CardMediaContainer(context: Context, attrs: AttributeSet? = null) : ViewGr
val childCount = rebuildChildInfo() val childCount = rebuildChildInfo()
var heightSum = 0 var heightSum = 0
if (childCount > 0) { if (childCount > 0) {
heightSum = if (childCount == 1) { heightSum = when (childCount) {
1 -> {
measure1Media(contentWidth, childIndices, ratioMultiplier) measure1Media(contentWidth, childIndices, ratioMultiplier)
} else if (childCount == 2) { }
2 -> {
measureGridMedia(childCount, 2, contentWidth, ratioMultiplier, horizontalSpacing, measureGridMedia(childCount, 2, contentWidth, ratioMultiplier, horizontalSpacing,
verticalSpacing, childIndices) verticalSpacing, childIndices)
} else if (childCount == 3) { }
3 -> {
measure3Media(contentWidth, horizontalSpacing, childIndices, ratioMultiplier) measure3Media(contentWidth, horizontalSpacing, childIndices, ratioMultiplier)
} else { }
else -> {
measureGridMedia(childCount, 2, contentWidth, measureGridMedia(childCount, 2, contentWidth,
WIDTH_HEIGHT_RATIO * ratioMultiplier, horizontalSpacing, verticalSpacing, childIndices) WIDTH_HEIGHT_RATIO * ratioMultiplier, horizontalSpacing, verticalSpacing, childIndices)
} }
}
if (contentHeight > 0) { if (contentHeight > 0) {
heightSum = contentHeight heightSum = contentHeight
} }

View File

@ -111,13 +111,17 @@ class IconActionButton(
fun IIconActionButton.updateColorFilter() { fun IIconActionButton.updateColorFilter() {
this as ImageView this as ImageView
if (isActivated) { when {
isActivated -> {
setColorFilter(activatedColor) setColorFilter(activatedColor)
} else if (isEnabled) { }
isEnabled -> {
setColorFilter(defaultColor) setColorFilter(defaultColor)
} else { }
else -> {
setColorFilter(disabledColor) setColorFilter(disabledColor)
} }
} }
} }
} }
}

View File

@ -76,13 +76,17 @@ class DraftViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
} else { } else {
contentView.drawEnd() contentView.drawEnd()
} }
if (summaryText != null) { when {
summaryText != null -> {
textView.spannable = summaryText textView.spannable = summaryText
} else if (draft.text.isNullOrEmpty()) { }
draft.text.isNullOrEmpty() -> {
textView.setText(R.string.empty_content) textView.setText(R.string.empty_content)
} else { }
else -> {
textView.spannable = draft.text textView.spannable = draft.text
} }
}
if (draft.timestamp > 0) { if (draft.timestamp > 0) {
val timeString = Utils.formatSameDayTime(context, draft.timestamp) val timeString = Utils.formatSameDayTime(context, draft.timestamp)

View File

@ -167,19 +167,23 @@ class DetailStatusViewHolder(
val quotedMedia = status.quoted_media val quotedMedia = status.quoted_media
if (quotedMedia?.isEmpty() != false) { when {
quotedMedia?.isEmpty() != false -> {
itemView.quotedMediaLabel.visibility = View.GONE itemView.quotedMediaLabel.visibility = View.GONE
itemView.quotedMediaPreview.visibility = View.GONE itemView.quotedMediaPreview.visibility = View.GONE
} else if (adapter.isDetailMediaExpanded) { }
adapter.isDetailMediaExpanded -> {
itemView.quotedMediaLabel.visibility = View.GONE itemView.quotedMediaLabel.visibility = View.GONE
itemView.quotedMediaPreview.visibility = View.VISIBLE itemView.quotedMediaPreview.visibility = View.VISIBLE
itemView.quotedMediaPreview.displayMedia(adapter.requestManager, itemView.quotedMediaPreview.displayMedia(adapter.requestManager,
media = quotedMedia, accountKey = status.account_key, media = quotedMedia, accountKey = status.account_key,
mediaClickListener = adapter.fragment) mediaClickListener = adapter.fragment)
} else { }
else -> {
itemView.quotedMediaLabel.visibility = View.VISIBLE itemView.quotedMediaLabel.visibility = View.VISIBLE
itemView.quotedMediaPreview.visibility = View.GONE itemView.quotedMediaPreview.visibility = View.GONE
} }
}
} else { } else {
itemView.quotedName.visibility = View.GONE itemView.quotedName.visibility = View.GONE
itemView.quotedText.visibility = View.VISIBLE itemView.quotedText.visibility = View.VISIBLE
@ -299,23 +303,27 @@ class DetailStatusViewHolder(
val media = status.media val media = status.media
if (media?.isEmpty() != false) { when {
media?.isEmpty() != false -> {
itemView.mediaPreviewContainer.visibility = View.GONE itemView.mediaPreviewContainer.visibility = View.GONE
itemView.mediaPreview.visibility = View.GONE itemView.mediaPreview.visibility = View.GONE
itemView.mediaPreviewLoad.visibility = View.GONE itemView.mediaPreviewLoad.visibility = View.GONE
itemView.mediaPreview.displayMedia() itemView.mediaPreview.displayMedia()
} else if (adapter.isDetailMediaExpanded) { }
adapter.isDetailMediaExpanded -> {
itemView.mediaPreviewContainer.visibility = View.VISIBLE itemView.mediaPreviewContainer.visibility = View.VISIBLE
itemView.mediaPreview.visibility = View.VISIBLE itemView.mediaPreview.visibility = View.VISIBLE
itemView.mediaPreviewLoad.visibility = View.GONE itemView.mediaPreviewLoad.visibility = View.GONE
itemView.mediaPreview.displayMedia(adapter.requestManager, media = media, itemView.mediaPreview.displayMedia(adapter.requestManager, media = media,
accountKey = status.account_key, mediaClickListener = adapter.fragment) accountKey = status.account_key, mediaClickListener = adapter.fragment)
} else { }
else -> {
itemView.mediaPreviewContainer.visibility = View.VISIBLE itemView.mediaPreviewContainer.visibility = View.VISIBLE
itemView.mediaPreview.visibility = View.GONE itemView.mediaPreview.visibility = View.GONE
itemView.mediaPreviewLoad.visibility = View.VISIBLE itemView.mediaPreviewLoad.visibility = View.VISIBLE
itemView.mediaPreview.displayMedia() itemView.mediaPreview.displayMedia()
} }
}
if (TwitterCardUtils.isCardSupported(status)) { if (TwitterCardUtils.isCardSupported(status)) {
val size = TwitterCardUtils.getCardSize(status.card!!) val size = TwitterCardUtils.getCardSize(status.card!!)

View File

@ -26,13 +26,17 @@ object AccountsSelectorTransformer : ViewPager.PageTransformer {
internal const val selectorAccountsCount: Int = 3 internal const val selectorAccountsCount: Int = 3
override fun transformPage(page: View, position: Float) { override fun transformPage(page: View, position: Float) {
if (position < 0) { when {
position < 0 -> {
page.alpha = 1 + position * selectorAccountsCount page.alpha = 1 + position * selectorAccountsCount
} else if (position > (selectorAccountsCount - 1f) / selectorAccountsCount) { }
position > (selectorAccountsCount - 1f) / selectorAccountsCount -> {
page.alpha = (1 - position) * selectorAccountsCount page.alpha = (1 - position) * selectorAccountsCount
} else { }
else -> {
page.alpha = 1f page.alpha = 1f
} }
} }
}
} }