如何在Android中使用Picasso加载ImageView的图片URL?


此示例演示了如何在Android中使用Picasso加载ImageView。

步骤1 - 在Android Studio中创建一个新项目,转到文件⇒新建项目,并填写所有必需的详细信息以创建新项目。

步骤2 - 项目中的Gradle脚本→单击build.gradle(模块:app)→添加依赖项 - Implementation ‘com.squareup.picasso−Picasso:2.5.2,然后单击“立即同步”。

步骤3 - 将以下代码添加到res/layout/activity_main.xml中。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="16dp"
   android:orientation="vertical"/>
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Load ImageView by URL"
      android:textStyle="bold"
      android:textColor="@color/colorPrimary"
      android:textSize="20sp" />
   <ImageView
      android:id="@+id/image_view"
      android:layout_width="fill_parent"
      android:layout_height="300dp"
      android:layout_marginTop="16dp" />
   <TextView
      android:layout_width="fill_parent"
      android:layout_height="match_parent"
      android:textSize="24sp"
      android:gravity="center|bottom"
      android:textStyle="bold" />
</LinearLayout>

步骤4 - 将以下代码添加到src/MainActivity.java中

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
   private ImageView imageView;
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      ImageView imageView = findViewById(R.id.image_view);
      String url = "https://images.pexels.com/photos/814499/pexels-photo814499.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
      Picasso.with(this).load(url).into(imageView);
   }
}

步骤5 - 将以下代码添加到androidManifest.xml中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <uses-permission android:name="android.permission.INTERNET" />
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

让我们尝试运行您的应用程序。我假设您已将您的实际Android移动设备连接到您的计算机。要从Android Studio运行应用程序,请打开项目中的一个活动文件,然后单击运行  工具栏中的图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕 -

点击这里下载项目代码。

更新于: 2019年8月1日

622 次查看

开启您的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.