如何使用 Picasso 在 Android 上通过 URL 加载 ImageView?

androidapps/applicationsmobile development

本示例演示了如何使用 Picasso 在 Android 上加载 ImageView。

步骤 1 - 在 Android Studio 中创建一个新项目,依次点击"文件">"新建项目",并填写所有必需信息以创建新项目。

步骤 2 - 从项目中添加 Gradle 脚本 - 点击 build.gradle(模块:app) - 添加依赖项 - ‘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 运行应用程序,请打开项目中的一个 Activity 文件,然后单击工具栏中的"运行"图标 。选择您的移动设备作为选项,然后选中您的移动设备,它将显示您的默认屏幕。 −


相关文章