Android(安卓)简单图片浏览器(疯狂Android讲义第三版)
16lz
2021-01-25
一个比较简单的DEMO
先说说我遇到的问题(新手)
如何添加图片和调用图片资源
添加图片资源:添加到工程文件夹drawable中(直接拖入无效,只能用Ctrl + C的方式。但是有人说他的Android Studio可是直接拖入,搞不懂)
调用图片资源:
- 在Android Studio的design页面中拖入一个ImageView,双击此组件,然后弹出一个页面,选择你需要的图片即可
- 直接在.xml代码中添加一个属性:
android:src="@drawable/ysx"
- 使用setImageResource() 方法改变图片内容
图片格式的问题
- 一直以为改掉图片的后缀就是改掉图片的格式,这使我把一张.jpg改成.png的时候是,就编译不通过了。(改格式需要使用特定的软件,不能单纯的改后缀。。)
最后贴个代码吧,简单好理解的。。(点击图片既可切换图片)
MainActivity代码:
package com.example.wen.myapplication;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.ImageView;public class MainActivity extends AppCompatActivity { int[] images = new int[]{ R.drawable.bee_16_lunch, R.drawable.x }; private ImageView imageView; private int cnt = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView =(ImageView) findViewById(R.id.imageView); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { imageView.setImageResource(images[++cnt % 2 ]); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }}
activity_main.xml代码:
"http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> "wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:src="@drawable/bee_16_lunch" /></RelativeLayout>
(这是我第一次用markdown写的,写得不太好喔~~)
更多相关文章
- 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
- Android(安卓)获取并显示远程图片 Picasso框架的使用
- Android中关于Notification及NotificationManger的详解
- android ImageView 的几点经验总结
- Android(安卓)Studio 使用Git创建本地分支和远程分支以及合并
- Android音乐播放器【安卓进化二十】
- android EventBus学习记录
- Android移动安全(一)Android混淆机制
- Android(安卓)中Canvas.drawBitmap()的使用