您的位置:首页 > 移动开发 > Android开发

Android点击Button切换多个图片显示

2017-12-08 23:36 344 查看
最近在自学Android,编译器用的是Android Studio,因为Eclipse + Android SDK + ADT配置了半天最后还报错找不到dx.jar,关键这个包真实存在,实在受不了直接用AS来学了,但不得不说AS写起来非常爽,咔咔咔 代码就出来了,但是。。用AS基础容易不打扎实。。

废话少说,上代码。

以下是activity_main.xml文件代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="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:orientation="vertical"
tools:context="com.example.administrator.myapplication.MainActivity"
android:weightSum="1">

<Button
android:id="@+id/button"
android:layout_width="100dp"
android:layout_height="60dp"
android:text="Button"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="121dp"
/>

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/female"/>

</LinearLayout>

布局效果如下(为不知火舞小姐姐打Call):



以下是MainActivity.java中的代码:

package com.example.administrator.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

Button btn;
TextView tv;
int i=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btn = (Button)findViewById(R.id.button);
tv = (TextView)findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (i) {
case 0:tv.setBackgroundResource(R.drawable.picture2);i++;break;
case 1:tv.setBackgroundResource(R.drawable.picture3);i++;break;
case 2:tv.setBackgroundResource(R.drawable.picture4);i++;break;
case 3:tv.setBackgroundResource(R.drawable.picture5);i++;break;
case 4:tv.setBackgroundResource(R.drawable.picture6);i++;break;
case 5:tv.setBackgroundResource(R.drawable.female);i++;break;
}
if(i>=6)
i=0;
}
});

}
}

说明:
1、按钮设置监听事件,监测到点击一次就显示一张图片,通过 i 的自增来实现。

2、因为是六张图所以i>6的时候清0,才能把保证点击按钮图片循环显示。

附上项目里六张图片的位置,在res的drawable里。



PS:Android还在自学中,目前菜鸟一枚,如有改进的地方请各路大神多多指点。O(∩_∩)O~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: