本文整理汇总了Scala中android.content.Context类的典型用法代码示例。如果您正苦于以下问题:Scala Context类的具体用法?Scala Context怎么用?Scala Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Context类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: MainActivity
//设置package包名称以及导入依赖的类
package $package$.activity
import $package$.api.UiService
import $package$.model.Ticker
import android.content.{Intent, Context}
import android.view.View
import android.widget.{TextView, ProgressBar, LinearLayout}
import macroid.FullDsl._
import macroid._
import android.app.Activity
import android.os.Bundle
class MainActivity extends Activity with Contexts[Activity] with MainActivityView with UiService {
override def onCreate(b: Bundle): Unit = {
super.onCreate(b)
setTitle("Hello world, $name$!")
setContentView(ui.get)
update
}
def update = api(_.pubticker("btcusd")) mapUi updateView
def updateView(t: Ticker) = runUi(
lastPriceSlot <~ text("Whoa! Bitcoin price is " + t.last_price)
)
}
trait MainActivityView {
var lastPriceSlot = slot[TextView]
def ui(implicit context: ActivityContext): Ui[LinearLayout] = {
l[LinearLayout](
w[TextView] <~ wire(lastPriceSlot)
)
}
}
示例2: FileManager
//设置package包名称以及导入依赖的类
package com.mishiranu.instantimage.util
import java.io.File
import android.content.Context
import android.webkit.MimeTypeMap
object FileManager {
def cleanup(context: Context): Unit = {
val time = System.currentTimeMillis - 24 * 60 * 60 * 1000
Option(context.getFilesDir.listFiles).getOrElse(Array())
.filter(_.lastModified < time)
.foreach(_.delete())
}
def obtainSimpleFileName(originalUriString: String): String = {
System.currentTimeMillis + "." + Option(originalUriString).map { uriString =>
val index = uriString.lastIndexOf('.')
if (index >= 0 && uriString.indexOf('/', index) == -1) uriString.substring(index + 1) else null
}.filter(e => e != null && !e.isEmpty && e.length <= 5).getOrElse("jpeg")
}
case class FileItem(contentId: Int, displayName: String, file: File) {
def mimeType: String = {
val extension = {
val index = displayName.lastIndexOf('.')
if (index >= 0) displayName.substring(index + 1) else "jpeg"
}
Option(MimeTypeMap.getSingleton.getMimeTypeFromExtension(extension))
.filter(_ != null)
.filter(_.isEmpty)
.getOrElse("image/jpeg")
}
}
def obtainFile(context: Context, originalUriString: String, contentId: Int): FileItem = {
val filesDir = context.getFilesDir
filesDir.mkdirs()
val displayName = contentId + "-" + obtainSimpleFileName(originalUriString)
FileItem(contentId, displayName, new File(filesDir, displayName))
}
def listFiles(context: Context): List[FileItem] = {
case class Data(file: File, splitted: Array[String])
Option(context.getFilesDir.listFiles).getOrElse(Array())
.map(f => Data(f, f.getName.split("-")))
.filter(_.splitted != null)
.filter(_.splitted.length == 2)
.map(d => FileItem(d.splitted(0).toInt, d.splitted(1), d.file)).toList
}
def findFile(context: Context, contentId: Int): Option[FileItem] = {
listFiles(context).find(_.contentId == contentId)
}
}
示例3: BorderSelectorDrawable
//设置package包名称以及导入依赖的类
package com.mishiranu.instantimage.graphics
import android.content.Context
import android.graphics.{Canvas, Color, Paint}
class BorderSelectorDrawable(context: Context) extends SelectorDrawable {
import BorderSelectorDrawable._
private val paint = new Paint(Paint.ANTI_ALIAS_FLAG)
paint.setColor(Color.BLACK)
private val density = context.getResources.getDisplayMetrics.density
private var selected = false
override def setSelected(selected: Boolean, animated: Boolean): Unit = {
this.selected = selected
invalidateSelf()
}
override def draw(canvas: Canvas): Unit = {
if (selected) {
canvas.drawColor(0x7f000000)
val bounds = getBounds
val thickness = (THICKNESS_DP * density).toInt
canvas.drawRect(bounds.top, bounds.left, bounds.right, bounds.top + thickness, paint)
canvas.drawRect(bounds.bottom - thickness, bounds.left, bounds.right, bounds.bottom, paint)
canvas.drawRect(bounds.top, bounds.left, bounds.left + thickness, bounds.bottom, paint)
canvas.drawRect(bounds.top, bounds.right - thickness, bounds.right, bounds.bottom, paint)
}
}
}
object BorderSelectorDrawable {
private val THICKNESS_DP = 2
}
示例4: FloatingActionMenuBehavior
//设置package包名称以及导入依赖的类
package com.github.shadowsocks.widget
import android.animation.ValueAnimator
import android.content.Context
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.CoordinatorLayout.Behavior
import android.support.design.widget.Snackbar.SnackbarLayout
import android.support.v4.view.animation.FastOutSlowInInterpolator
import android.util.AttributeSet
import android.view.View
import com.github.clans.fab.FloatingActionMenu
import scala.collection.JavaConverters._
class FloatingActionMenuBehavior(context: Context, attrs: AttributeSet)
extends Behavior[FloatingActionMenu](context, attrs) {
private var fabTranslationYAnimator: ValueAnimator = _
private var fabTranslationY: Float = _
override def layoutDependsOn(parent: CoordinatorLayout, child: FloatingActionMenu, dependency: View) =
dependency.isInstanceOf[SnackbarLayout]
override def onDependentViewChanged(parent: CoordinatorLayout, child: FloatingActionMenu, dependency: View) = {
dependency match {
case _: SnackbarLayout =>
var targetTransY = parent.getDependencies(child).asScala
.filter(view => view.isInstanceOf[SnackbarLayout] && parent.doViewsOverlap(child, view))
.map(view => view.getTranslationY - view.getHeight).reduceOption(_ min _).getOrElse(0F)
if (targetTransY > 0) targetTransY = 0
if (fabTranslationY != targetTransY) {
val currentTransY = child.getTranslationY
if (fabTranslationYAnimator != null && fabTranslationYAnimator.isRunning) fabTranslationYAnimator.cancel
if (child.isShown && Math.abs(currentTransY - targetTransY) > child.getHeight * 0.667F) {
if (fabTranslationYAnimator == null) {
fabTranslationYAnimator = new ValueAnimator
fabTranslationYAnimator.setInterpolator(new FastOutSlowInInterpolator)
fabTranslationYAnimator.addUpdateListener(animation =>
child.setTranslationY(animation.getAnimatedValue.asInstanceOf[Float]))
}
fabTranslationYAnimator.setFloatValues(currentTransY, targetTransY)
fabTranslationYAnimator.start
} else child.setTranslationY(targetTransY)
fabTranslationY = targetTransY
}
}
false
}
override def onStartNestedScroll(parent: CoordinatorLayout, child: FloatingActionMenu, directTargetChild: View,
target: View, nestedScrollAxes: Int) = true
override def onNestedScroll(parent: CoordinatorLayout, child: FloatingActionMenu, target: View, dxConsumed: Int,
dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int) = {
super.onNestedScroll(parent, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed)
val dy = dyConsumed + dyUnconsumed
if (child.isMenuButtonHidden) {
if (dy < 0) child.showMenuButton(true)
} else if (dy > 0) child.hideMenuButton(true)
}
}
示例5: NumberPickerPreferenceDialogFragment
//设置package包名称以及导入依赖的类
package be.mygod.preference
import android.content.Context
import android.support.v14.preference.PreferenceDialogFragment
import android.view.{View, ViewGroup}
class NumberPickerPreferenceDialogFragment extends PreferenceDialogFragment {
private lazy val preference = getPreference.asInstanceOf[NumberPickerPreference]
private lazy val picker = preference.picker
override protected def onCreateDialogView(context: Context) = {
val parent = picker.getParent.asInstanceOf[ViewGroup]
if (parent != null) parent.removeView(picker)
picker
}
override protected def onBindDialogView(view: View) {
super.onBindDialogView(view)
picker.setValue(preference.getValue)
}
override protected def needInputMethod = true
def onDialogClosed(positiveResult: Boolean) {
picker.clearFocus // commit changes
if (positiveResult) {
val value = picker.getValue
if (preference.callChangeListener(value)) preference.setValue(value)
}
}
}
示例6: EditTextPreferenceDialogFragment
//设置package包名称以及导入依赖的类
package be.mygod.preference
import android.content.Context
import android.support.v14.preference.PreferenceDialogFragment
import android.view.{View, ViewGroup}
class EditTextPreferenceDialogFragment extends PreferenceDialogFragment {
private lazy val preference = getPreference.asInstanceOf[EditTextPreference]
private lazy val editText = preference.editText
override protected def onCreateDialogView(context: Context) = {
val parent = editText.getParent.asInstanceOf[ViewGroup]
if (parent != null) parent.removeView(editText)
editText
}
override protected def onBindDialogView(view: View) {
super.onBindDialogView(view)
editText.setText(preference.getText)
val text = editText.getText
if (text != null) editText.setSelection(0, text.length)
}
override protected def needInputMethod = true
def onDialogClosed(positiveResult: Boolean) = if (positiveResult) {
val value = editText.getText.toString
if (preference.callChangeListener(value)) preference.setText(value)
}
}
示例7: EditTextPreference
//设置package包名称以及导入依赖的类
package be.mygod.preference
import android.content.Context
import android.support.v7.preference.{EditTextPreference => Parent}
import android.support.v7.widget.AppCompatEditText
import android.text.InputType
import android.util.AttributeSet
class EditTextPreference(context: Context, attrs: AttributeSet = null) extends Parent(context, attrs)
with SummaryPreference {
val editText = new AppCompatEditText(context, attrs)
editText.setId(android.R.id.edit)
override protected def getSummaryValue = {
var text = getText
if (text == null) text = ""
val inputType = editText.getInputType
if (inputType == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) ||
inputType == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD) ||
inputType == (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD))
"\u2022" * text.length else text
}
override def setText(text: String) = {
super.setText(text)
notifyChanged
}
}
示例8: NumberPickerPreference
//设置package包名称以及导入依赖的类
package be.mygod.preference
import android.content.Context
import android.content.res.TypedArray
import android.support.v7.preference.DialogPreference
import android.util.AttributeSet
import android.view.ContextThemeWrapper
import android.widget.NumberPicker
import com.github.shadowsocks.R
class NumberPickerPreference(private val context: Context, attrs: AttributeSet = null)
extends DialogPreference(context, attrs) with SummaryPreference {
private[preference] val picker = new NumberPicker(new ContextThemeWrapper(context, R.style.NumberPickerStyle))
private var value: Int = _
{
val a: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.NumberPickerPreference)
setMin(a.getInt(R.styleable.NumberPickerPreference_min, 0))
setMax(a.getInt(R.styleable.NumberPickerPreference_max, Int.MaxValue - 1))
a.recycle
}
def getValue = value
def getMin = if (picker == null) 0 else picker.getMinValue
def getMax = picker.getMaxValue
def setValue(i: Int) {
if (i == value) return
picker.setValue(i)
value = picker.getValue
persistInt(value)
notifyChanged
}
def setMin(value: Int) = picker.setMinValue(value)
def setMax(value: Int) = picker.setMaxValue(value)
override protected def onGetDefaultValue(a: TypedArray, index: Int): AnyRef =
a.getInt(index, getMin).asInstanceOf[AnyRef]
override protected def onSetInitialValue(restorePersistedValue: Boolean, defaultValue: Any) {
val default = defaultValue.asInstanceOf[Int]
setValue(if (restorePersistedValue) getPersistedInt(default) else default)
}
protected def getSummaryValue: AnyRef = getValue.asInstanceOf[AnyRef]
}
示例9: AlarmBroadcastReceiver
//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.receiver
import android.app.{Notification, NotificationManager, PendingIntent}
import android.content.{BroadcastReceiver, Context, Intent}
import android.support.v4.app.NotificationCompat
import android.text.TextUtils
import com.android.perrier1034.post_it_note.db.dao.{PageStore, NoteStore}
import com.android.perrier1034.post_it_note.model.NoteRealm
import com.android.perrier1034.post_it_note.ui.PageManager
import com.android.perrier1034.post_it_note.util.AlarmUtil
import com.android.perrier1034.post_it_note.{App, R}
object AlarmBroadcastReceiver {
val KEY_INTENT_ALARM_USUAL = "KEY_INTENT_USUAL"
val KEY_INTENT_PAGE_ORDER = "KEY_INTENT_PAGE_ORDER"
}
class AlarmBroadcastReceiver extends BroadcastReceiver {
override def onReceive(context: Context, receivedIntent: Intent) {
receivedIntent.getAction match {
case Intent.ACTION_PACKAGE_REPLACED | Intent.ACTION_BOOT_COMPLETED =>
NoteStore.rebootAlarmsRealm()
case AlarmBroadcastReceiver.KEY_INTENT_ALARM_USUAL =>
val id = receivedIntent.getLongExtra(AlarmUtil.alarmIntentDataKey, -1)
val note = NoteStore.findByIdRealm(id)
val pageOrder = PageStore .getPageOrderById(note.parentId)
if (note.inRubbish != 1) {
val nm = App.getInstance.getSystemService(Context.NOTIFICATION_SERVICE).asInstanceOf[NotificationManager]
val notif = makeNotification(note, pageOrder)
nm.notify(id.asInstanceOf[Int], notif)
}
NoteStore.clearAlarmRealm(id)
case _ =>
}
}
private def makeNotification(note: NoteRealm, pageOrder: Int): Notification = {
val in = new Intent(App.getInstance, classOf[PageManager])
in.putExtra(AlarmBroadcastReceiver.KEY_INTENT_PAGE_ORDER, pageOrder)
val pi = PendingIntent.getActivity(App.getInstance, 0, in, PendingIntent.FLAG_UPDATE_CURRENT)
val builder = new NotificationCompat.Builder(App.getInstance)
val content = if (TextUtils.isEmpty(note.checkItems)) "(check list)" else note.content
builder
.setSmallIcon(R.drawable.ic_launcher)
.setTicker(content)
.setContentText(content)
.setWhen(System.currentTimeMillis).setAutoCancel(true)
.setContentIntent(pi)
.setContentTitle(if (TextUtils.isEmpty(note.title)) "No title" else note.title)
.build()
}
}
示例10: ScrollViewEx
//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.ui.views
import android.util.AttributeSet
import android.content.Context
import android.view.MotionEvent
import android.widget.ScrollView
class ScrollViewEx(ctx: Context, attrs: AttributeSet) extends ScrollView(ctx, attrs) {
val DISTANCE = 20f
var downX = 0f
var downY = 0f
def this(context: Context) = this(context, null)
override def onInterceptTouchEvent(event: MotionEvent): Boolean = {
// We have to call below to do scrolling properly.
// So anyway call it and alloc the return value
val b = super.onInterceptTouchEvent(event)
// save touched position when "ACTION_DOWN" !
if (event.getAction == MotionEvent.ACTION_DOWN) {
downX = event.getX
downY = event.getY
}
// calc distance
if (event.getAction == MotionEvent.ACTION_UP) {
return (Math.abs(event.getY - downY) > DISTANCE) || (Math.abs(event.getX - downX) > DISTANCE)
}
b
}
}
示例11: HackyEditText
//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.ui.views
import android.graphics.Canvas
import android.os.{Looper, Handler}
import android.support.v7.widget.AppCompatEditText
import android.util.AttributeSet
import android.content.Context
import android.view.inputmethod.InputMethodManager
import com.android.perrier1034.post_it_note.App
class HackyEditText(ctx: Context, attrs: AttributeSet) extends AppCompatEditText(ctx, attrs) {
def this(ctx: Context) = this(ctx, null)
var isTarget = false
setWillNotDraw(false)
override def onDraw(canvas: Canvas ) {
super.onDraw(canvas)
if (isTarget) {
isTarget = false
requestFocus()
// setShowSoftInputOnFocus(true)
if (isInputMethodTarget) {
showKeyBoard()
} else{
// ugly hack but I have no choice.
// this occur when CheckListAdapter.appendNewRow() called on creating new check-list-note
new Thread(new Runnable() {
override def run() = {
new Handler(Looper.getMainLooper).postDelayed(new Runnable() {
def run() = showKeyBoard()
}, 50)
}
}).start()
}
}
}
def showKeyBoard() {
val imm = getContext.getSystemService(Context.INPUT_METHOD_SERVICE).asInstanceOf[InputMethodManager]
imm.showSoftInput(this, InputMethodManager.SHOW_FORCED)
}
}
示例12: HackyViewPager
//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.ui.views
import android.content.Context
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.MotionEvent
class HackyViewPager(ctx: Context, attrs: AttributeSet) extends ViewPager(ctx, attrs) {
def this(context: Context) = this(context, null)
var isLocked = false
override def onInterceptTouchEvent(ev: MotionEvent): Boolean = {
if (!isLocked) {
try {
return super.onInterceptTouchEvent(ev)
} catch {
case e: IllegalArgumentException =>
e.printStackTrace()
return false
}
}
false
}
override def onTouchEvent(event: MotionEvent): Boolean = {
if (!isLocked) {
return super.onTouchEvent(event)
}
false
}
def toggleLock() {
isLocked = !isLocked
}
def setLocked(b: Boolean ) {
isLocked = b
}
}
示例13: DividerAdder
//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.ui
import android.content.Context
import android.content.res.TypedArray
import android.graphics.drawable.Drawable
import android.graphics.{Canvas, Rect}
import android.support.v7.widget.RecyclerView
object DividerAdder {
private val ATTRS: Array[Int] = Array[Int](android.R.attr.listDivider)
}
class DividerAdder extends RecyclerView.ItemDecoration {
private var mDivider: Drawable = null
def this(context: Context) {
this()
val array: TypedArray = context.obtainStyledAttributes(DividerAdder.ATTRS)
mDivider = array.getDrawable(0)
array.recycle
}
@SuppressWarnings(Array("deplicated"))
override def getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight)
}
override def onDraw(c: Canvas, parent: RecyclerView) {
drawVertical(c, parent)
}
def drawVertical(c: Canvas, parent: RecyclerView) {
val left: Int = parent.getPaddingLeft
val right: Int = parent.getWidth - parent.getPaddingRight
val childCount: Int = parent.getChildCount
for (i <- 0 until parent.getChildCount) {
val child = parent.getChildAt(i)
val params = child.getLayoutParams.asInstanceOf[RecyclerView.LayoutParams]
val top = child.getBottom + params.bottomMargin
val bottom = top + mDivider.getIntrinsicHeight
mDivider.setBounds(left, top, right, bottom)
mDivider.draw(c)
}
}
}
示例14: AlarmUtil
//设置package包名称以及导入依赖的类
package com.android.perrier1034.post_it_note.util
import java.util.{Calendar, TimeZone}
import android.app.{AlarmManager, PendingIntent}
import android.content.{Context, Intent}
import com.android.perrier1034.post_it_note.App
import com.android.perrier1034.post_it_note.receiver.AlarmBroadcastReceiver
object AlarmUtil {
val alarmIntentDataKey = "alarmIntentDataKey "
def set(id: Long, year: Int, month: Int, date: Int) = {
val cal = Calendar.getInstance
cal.setTimeInMillis(System.currentTimeMillis)
cal.setTimeZone(TimeZone.getDefault)
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, month)
cal.set(Calendar.DAY_OF_MONTH, date)
cal.set(Calendar.HOUR_OF_DAY, 0)
cal.set(Calendar.MINUTE, 0)
val intent = new Intent(App.getInstance, classOf[AlarmBroadcastReceiver])
intent.putExtra(alarmIntentDataKey, id)
intent.setAction(AlarmBroadcastReceiver.KEY_INTENT_ALARM_USUAL)
val pendingIntent = PendingIntent.getBroadcast(App.getInstance, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)
val alarmManager = App.getInstance.getSystemService(Context.ALARM_SERVICE).asInstanceOf[AlarmManager]
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis, pendingIntent)
}
def clear(noteId: Long) = {
val intent = new Intent(App.getInstance, classOf[AlarmBroadcastReceiver])
intent.putExtra(alarmIntentDataKey, noteId)
val pendingIntent = PendingIntent.getBroadcast(App.getInstance, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)
val alarmManager = App.getInstance.getSystemService(Context.ALARM_SERVICE).asInstanceOf[AlarmManager]
alarmManager.cancel(pendingIntent)
}
}
示例15: AndroidVaultConfigurationProvider
//设置package包名称以及导入依赖的类
package one.lockstep.vault.spi.impl.android
import java.io.File
import one.lockstep.util._
import one.lockstep.vault.spi
import android.content.Context
import scala.util.control.NonFatal
class AndroidVaultConfigurationProvider(defaultContext: => Context)
extends spi.VaultConfigurationProvider
with Logging {
def nonPersistent = sys.props.get("lockstep.nonpersistent").exists(value => value.isEmpty || value == "true")
def workDirOpt(context: Context): Option[File] =
if (nonPersistent) {
logger.debug("System property 'lockstep.nonpersistent' detected, vault will not be persisted.")
None
} else {
val workDir = context.getDir("lockstep", Context.MODE_PRIVATE)
logger.debug("setting work directory to " + workDir)
Some(workDir)
}
override def vaultConfig(): spi.VaultConfiguration =
try {
val context = defaultContext
new spi.VaultConfiguration(workDirOpt(context).orNull)
} catch {
case NonFatal(cause) => throw new RuntimeException("vault configuration failed", cause)
}
}
object AndroidVaultConfigurationProvider
extends AndroidVaultConfigurationProvider(AndroidUtil.currentApplication)