Android開發實現的圖片點擊切換功能示例

這篇文章主要介紹了Android開發實現的圖片點擊切換功能,涉及Android ImageView組件創建、佈局及實現圖形切換相關操作技巧,需要的朋友可以參考下

本文實例講述了Android開發實現的圖片點擊切換功能。分享給大家供大家參考,具體如下:

java 代碼

public class MainActivity extends AppCompatActivity {
  //定義一個訪問圖片的數組
  int[] images = new int[]{
      R.drawable.java,
      R.drawable.javaee,
      R.drawable.swift,
      R.drawable.ajax,
      R.drawable.html,
  };
  //用於圖片切換
  int currenImg = 0;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //獲取Linearlayout佈局容器
    LinearLayout main = (LinearLayout) findViewById(R.id.root);
    //創建ImageView組件
    final ImageView image = new ImageView(this);
    //將ImageView組建添加到linearlayout佈局中
    main.addView(image);
    //初始化顯示第一張圖片
    image.setImageResource(images[0]);
    image.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        image.setImageResource(images[++currenImg % images.length]);
      }
    });
  }
}

xml 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/root"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  tools:context=".MainActivity">
</LinearLayout>

效果

更多關於Android相關內容感興趣的讀者可查看本站專題:《Android圖形與圖像處理技巧總結》、《Android開發入門與進階教程》、《Android調試技巧與常見問題解決方法彙總》、《Android基本組件用法總結》、《Android視圖View技巧總結》、《Android佈局layout技巧總結》及《Android控件用法總結

希望本文所述對大家Android程序設計有所幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章