[Kotlin&Anko开发Android入门学习笔记]-02Kotlin如何使用Android第三方库

1 篇文章 0 订阅
1 篇文章 0 订阅

一、背景说明

我们想将我们之前的项目,使用Kotlin重构,那么,在原来项目,会有一些第三方库(或者自己封装的自定义控件),我们总不能将人家的库也给重新用Kotlin重写吧。由于Kotlin支持Java代码,所以,主要思路是,使用Anko将我们要用到的库扩展,然后,需要用到的库中的方法属性,根据库文档进行适当的Kotlin调用。我将使用Fresco的SimpleDraweeView这个控件进行简单的举例。

二、配置SimpleDraweeView

关于Fresco,可以参考最新的文档进行相应的配置。首先配置app/build.gradle:

  
  
  1. compile 'com.facebook.fresco:fresco:0.8.1+'

然后在AndroidMainfest中配置网络权限:

  
  
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="top.xiexiaodong.hellokotlin">
  4. <uses-permission android:name="android.permission.INTERNET"/>
  5. <application
  6. android:allowBackup="true"
  7. android:icon="@mipmap/ic_launcher"
  8. android:label="@string/app_name"
  9. android:supportsRtl="true"
  10. android:theme="@style/AppTheme">
  11. <activity android:name=".MainActivity">
  12. <intent-filter>
  13. <action android:name="android.intent.action.MAIN" />
  14. <category android:name="android.intent.category.LAUNCHER" />
  15. </intent-filter>
  16. </activity>
  17. </application>
  18. </manifest>

这样我们就可以使用SimpleDraweeView控件了。

三、添加SimpleDraweeView的Anko扩展

这里我们添加到MainActivity.kt中:

  
  
  1. import android.support.v7.app.AppCompatActivity
  2. import android.os.Bundle
  3. import android.view.ViewManager
  4. import com.facebook.drawee.view.SimpleDraweeView
  5. import org.jetbrains.anko.*
  6. import org.jetbrains.anko.custom.ankoView
  7. class MainActivity : AppCompatActivity() {
  8. override fun onCreate(savedInstanceState: Bundle?) {
  9. super.onCreate(savedInstanceState)
  10. MainActivityUi().setContentView(this)
  11. }
  12. }
  13. class MainActivityUi : AnkoComponent<MainActivity> {
  14. override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
  15. verticalLayout {
  16. textView("Hello Kotlin!")
  17. button("Click me") {
  18. onClick {
  19. toast("Oh, You clicked me!")
  20. }
  21. }
  22. }
  23. }
  24. }
  25. public inline fun ViewManager.simpleDraweeView(theme: Int = 0) = simpleDraweeView(theme) {}
  26. public inline fun ViewManager.simpleDraweeView(theme: Int = 0, init: SimpleDraweeView.() -> Unit) = ankoView({ SimpleDraweeView(it) }, init)

我们在View中使用SimpleDraweeView,则使用内置函数ViewManager.新控件名称添加扩展,相应的,我们可以将Activity和Context都添加上去,代码如下:

  
  
  1. public inline fun Activity.simpleDraweeView(theme: Int = 0) = simpleDraweeView(theme) {}
  2. public inline fun Activity.simpleDraweeView(theme: Int = 0, init: SimpleDraweeView.() -> Unit) = ankoView({ SimpleDraweeView(it) }, init)
  3. public inline fun Context.simpleDraweeView(theme: Int = 0) = simpleDraweeView(theme) {}
  4. public inline fun Context.simpleDraweeView(theme: Int = 0, init: SimpleDraweeView.() -> Unit) = ankoView({ SimpleDraweeView(it) }, init)

这样,我们就可以在布局中使用SimpleDraweeView了:

  
  
  1. class MainActivityUi : AnkoComponent<MainActivity> {
  2. override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
  3. verticalLayout {
  4. textView("Hello Kotlin!")
  5. button("Click me") {
  6. onClick {
  7. toast("Oh, You clicked me!")
  8. }
  9. }
  10. simpleDraweeView().lparams(width = matchParent, height = matchParent) {
  11. }.apply {
  12. setImageURI(Uri.parse("http://avatar.csdn.net/7/2/A/3_a191030148.jpg"), null)
  13. hierarchy.setFadeDuration(300)
  14. hierarchy.setActualImageScaleType(ScalingUtils.ScaleType.FIT_XY)
  15. }
  16. }
  17. }
  18. }


最后,我们还要在使用SimpleDraweeView之前,初始化Fresco,这里放在了MainActivity onCreate()方法中了:

  
  
  1. class MainActivity : AppCompatActivity() {
  2. override fun onCreate(savedInstanceState: Bundle?) {
  3. super.onCreate(savedInstanceState)
  4. Fresco.initialize(this)
  5. MainActivityUi().setContentView(this)
  6. }
  7. }

其中,hierarchy.setFadeDuration()诸如此类的第三方库才会提供的属性设置,我是通过Fresco官方文档,参考Java代码来调用的,使用方法和Java差不多,在这里提供一下参考。我们运行一下程序看看效果:


有淡入效果,可以修改为3000,效果更明显。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
This library aims to overcome the limitations of Toasts and Snackbars, while reducing the complexity of your layouts.A customisable Alert view is dynamically added to the Decor View of the Window, overlaying all content.Gradledependencies {     implementation 'com.tapadoo.android:alerter:2.0.4'}UsageWith simplicity in mind, the Alerter employs the builder pattern to facilitate easy integration into any app.From an Activity -Alerter.create(this)        .setTitle("Alert Title")        .setText("Alert text...")        .show();Or from a Fragment -Alerter.create(getActivity())        .setTitle("Alert Title")        .setText("Alert text...")        .show();To check if an alert is showing -Alerter.isShowing();To hide a currently showing Alert -Alerter.hide();CustomisationBackground ColourAlerter.create(this)        .setTitle("Alert Title")        .setText("Alert text...")        .setBackgroundColorRes(R.color.colorAccent) // or setBackgroundColorInt(Color.CYAN)        .show();IconAlerter.create(this)        .setText("Alert text...")        .setIcon(R.drawable.alerter_ic_mail_outline)        .setIconColorFilter(0) // Optional - Removes white tint        .show();On screen duration, in millisecondsAlerter.create(this)        .setTitle("Alert Title")        .setText("Alert text...")        .setDuration(10000)        .show();Without titleAlerter.create(this)        .setText("Alert text...")        .show();Adding an On Click Listener Alerter.create(ExampleActivity.this)         .setTitle("Alert Title")         .setText("Alert text...")         .setDuration(10000)         .setOnClickListener(new View.OnClickListener() {                         @Override             public void onClick(View view) {                                 Toast.makeText(ExampleActivity.this, "OnClick Called", Toast.LENGTH_LONG).show();             }         })         .show();Verbose text Alerter.create(ExampleActivity.this)         .setTitle("Alert Title")         .setText("The alert scales to accommodate larger bodies of text. "                   "The alert scales to accommodate larger bodies of text. "                   "The alert scales to accommodate larger bodies of text.")         .show();Visibility Callbacks Alerter.create(ExampleActivity.this)         .setTitle("Alert Title")         .setOnShowListener(new OnShowAlertListener() {                      @Override             public void onShow() {                                 Toast.makeText(ExampleActivity.this, "Alert Shown", Toast.LENGTH_LONG).show();             }         })         .setOnHideListener(new OnHideAlertListener() {                         @Override             public void onHide() {                                 Toast.makeText(ExampleActivity.this, "Alert Hidden", Toast.LENGTH_LONG).show();             }          })         .show();Custom Fonts and Text Appearance Alerter.create(ExampleActivity.this)                 .setTitle("Alert Title")                 .setTitleAppearance(R.style.AlertTextAppearance_Title)                 .setTitleTypeface(Typeface.createFromAsset(getAssets(), "Pacifico-Regular.ttf"))                 .setText("Alert text...")                 .setTextAppearance(R.style.AlertTextAppearance_Text)                 .setTextTypeface(Typeface.createFromAsset(getAssets(), "ScopeOne-Regular.ttf"))                 .show();Swipe to Dismiss Alerter.create(ExampleActivity.this)                 .setTitle("Alert Title")                 .setText("Alert text...")                 .enableSwipeToDismiss()                 .show();Progress BarAlerter.create(ExampleActivity.this)                 .setTitle("Alert Title")                 .setText("Alert text...")                 .enableProgress(true)                 .setProgressColorRes(R.color.colorAccent)                 .show();

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值