Android Studio点击按钮更换背景图片(照片固定)
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.mybeijing.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/aa"/>
</LinearLayout>
java
package com.example.mybeijing;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
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.bb);i++;break;
case 1:tv.setBackgroundResource(R.drawable.cc);i++;break;
case 2:tv.setBackgroundResource(R.drawable.dd);i++;break;
case 3:tv.setBackgroundResource(R.drawable.ee);i++;break;
case 4:tv.setBackgroundResource(R.drawable.ff);i++;break;
}
if(i>=5)
i=0;
}
});
}
}