1.ImageView
1.1activity_image_scale.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:orientation="vertical"> <ImageView android:id="@+id/iv_scale" android:layout_width="match_parent" android:layout_height="220dp" android:layout_marginTop="5dp" android:src="@drawable/apple" android:scaleType="centerInside"/> <!-- android:src="@drawable/apple" --> </LinearLayout>
1.2ImageScaleActivity.java
package com.example.chapter03; import androidx.appcompat.app.AppCompatActivity; import android.media.Image; import android.os.Bundle; import android.widget.ImageView; public class ImageScaleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_scale); ImageView iv_scale = findViewById(R.id.iv_scale); iv_scale.setImageResource(R.drawable.apple); iv_scale.setScaleType(ImageView.ScaleType.CENTER); } }
1.3效果
2.ImageButton
2.1activity_image_button.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:orientation="vertical"> <ImageButton android:layout_width="match_parent" android:layout_height="80dp" android:src="@drawable/sqrt" android:scaleType="fitCenter"/> </LinearLayout>
2.2效果
3.同时展示文本与图像
3.1activity_image_text.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:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图标在左" android:drawableLeft="@drawable/ic_about" android:background="#FFFFFF" android:drawablePadding="5dp"/> </LinearLayout>
3.2themes.xml
<resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar.Bridge"> <!-- Primary brand color. --> <item name="colorPrimary">@color/purple_500</item> <item name="colorPrimaryVariant">@color/purple_700</item> <item name="colorOnPrimary">@color/white</item> <!-- Secondary brand color. --> <item name="colorSecondary">@color/teal_200</item> <item name="colorSecondaryVariant">@color/teal_700</item> <item name="colorOnSecondary">@color/black</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> </resources>
3.3效果