安卓可以支持两种图像格式 jpg 和png
首先需要拷贝图像文件到res目录下的drawer文件夹下
命名要注意只能有数字字母和下划线,不可以用“-”
在编辑窗口的界面中插入图像显示控件
更改ID使用图像编辑界面调整大小(使用线性布局)
其中XML文件内容:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="test testv"
android:textSize="24sp" />
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="duanlianda"
android:textSize="24sp" />
<ImageView
android:id="@+id/im_ebook"
android:layout_width="wrap_content"
android:layout_height="221dp"
app:srcCompat="@drawable/im_demo" />
</LinearLayout>
在 MainActivity 里面做一些更改:
package com.example.dlp.myapplication;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 显示图片信息
ImageView imageViewSETSETSET = findViewById(R.id.im_ebook);
Drawable image_ebook = getDrawable(R.drawable.im_demo);
imageViewSETSETSET.setImageDrawable(image_ebook);
/*显示文字信息*/
View view = this.findViewById(R.id.textView);
// 使用根据ID寻找 视窗的方法找到控件 控件的类是一个View的类型
// 准确地说是父类类型 现在装换为Textview类的对象
TextView textVieww = (TextView)view;
// 强制转换View类型的变量为TestView类型的变量
textVieww.setText("duanlianda hahaha");
}
}
其中关键部分为:
// 显示图片信息
ImageView imageViewSETSETSET = findViewById(R.id.im_ebook);
Drawable image_ebook = getDrawable(R.drawable.im_demo);
imageViewSETSETSET.setImageDrawable(image_ebook);
// 显示图片信息
1 ImageView imageViewSETSETSET = findViewById(R.id.im_ebook);
新建一个ImageView的对象(图像设置器) imageViewSETSETSET使用到的是通过Id寻找到的资源
2 Drawable image_ebook = getDrawable(R.drawable.im_demo);
新建一个Drawable 对象 image_ebook ,
3 imageViewSETSETSET.setImageDrawable(image_ebook);
使用1中获取的图像设置器,利用2中得到的Draweable对象将图像显示出来
结果: