kotlin 如何将uri转换为可绘制的整数?

5jvtdoz2  于 2022-12-19  发布在  Kotlin
关注(0)|答案(1)|浏览(113)

我正在处理小部件,我需要在AppWidgetProvider中使用这个views.setImageViewResource方法,但是这个方法需要整数,但是我有URI,我该如何解决这个问题?

class AppWidgetBroadcast : AppWidgetProvider() {
private lateinit var database: DatabaseReference
private lateinit var mydatabase: FirebaseDatabase

override fun onUpdate(
    context: Context,
    appWidgetManager: AppWidgetManager,
    appWidgetIds: IntArray
) {
    // Perform this loop procedure for each widget that belongs to this
    // provider.
    appWidgetIds.forEach { appWidgetId ->
        // Create an Intent to launch ExampleActivity.
        val pendingIntent: PendingIntent = PendingIntent.getActivity(
            /* context = */ context,
            /* requestCode = */  0,
            /* intent = */ Intent(context, WidgetDetailsActivity::class.java),
            /* flags = */ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        // Get the layout for the widget and attach an on-click listener
        // to the button.
        val string="sa"
        val uri:String="myUri"
        var imageuri: Uri = Uri.parse(uri)
        val views: RemoteViews = RemoteViews(context.packageName,R.layout.activity_widget_details).apply {
            setOnClickPendingIntent(R.id.fullImageWidget, pendingIntent)

        }


        // Tell the AppWidgetManager to perform an update on the current
        // widget.
        //views.setImageViewUri(R.id.fullImageWidget,null)

        views.setImageViewUri(R.id.fullImageWidget,imageuri)
        appWidgetManager.updateAppWidget(appWidgetId, views)
    }
}

}

rggaifut

rggaifut1#

如果您的URI属于此类型:第一个月
所以你在你的项目中使用这段代码。它会对你有帮助。

public Drawable getDrawableFromUri(Activity activity, Uri uri) {
        try {
            InputStream inputStream = activity.getContentResolver().openInputStream(uri);
            return Drawable.createFromStream(inputStream, uri.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

如果您的URI属于此类型:https://url.image.jpg
因此,在项目中使用Glide库加载图像。

  • build.gradle
repositories {
  google()
  mavenCentral()
}

dependencies {
  implementation 'com.github.bumptech.glide:glide:4.14.2'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.14.2'
}
  • activity.java
String URL = "https://media.istockphoto.com/id/1162019476/tr/fotoğraf/oyuncak-yarış-arabasında-boy-ve-köpek.jpg?s=1024x1024&w=is&k=20&c=TxRP45SO7Eja8IKQ0KFqHZAbzXuvWWVD3sLsQUpSc-A="

 Glide
    .with(YOUR_CONTEXT)
    .load(URL)
    .into(YOUR_IMAGE_VIEW);

相关问题