前端xml代码如下,使用FrameLayout布局。
<FrameLayout
android:id="@+id/fl"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="300dp"
android:id="@+id/iv1"
android:src="@drawable/imgshouye"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="300dp"
android:id="@+id/iv2"
android:src="@drawable/looking"
android:visibility="invisible"/> //设置图片不可见,默认可见
</FrameLayout>
后端代码
public class MainActivity extends AppCompatActivity {
private FrameLayout fl; //需要用来设置点击事件
private ImageView iv1;
private ImageView iv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fl = findViewById(R.id.fl);
iv1 = findViewById(R.id.iv1);
iv2 = findViewById(R.id.iv2);
show1();
fl.setOnClickListener(new View.OnClickListener() { //设置点击事件判定显示的图片
@Override
public void onClick(View v) {
if(iv1.getVisibility()==View.VISIBLE){
show2();
}else{
show1();
}
}
});
}
public void show1(){ //设置图一可见,图二不可见,与shou2()相反
iv1.setVisibility(View.VISIBLE);
iv2.setVisibility(View.INVISIBLE);
}
public void show2(){
iv2.setVisibility(View.VISIBLE);
iv1.setVisibility(View.INVISIBLE);
}
}