●V(View)=>ImageView
1.一定要英文名字
2.要事先存檔,支援多種檔案格式ex:png.gif.jpg...
3.把檔案copy然後可以直接在專案的drawable資料夾上按右鍵選貼上,確定圖片的放置位置後,就會發現檔案已經copy好了
實作(一)用兩個按鈕切換圖片
1.版面做兩個button,然後加入一個imageView,選定要出現的第一張照片
 
2.設定id(pre/next/img)
**onclick=>android:onclick="",可以直接自己輸入
 
3.抓id
**View是所有操作元件的父類別, (View v)是代表在等一個View物件進來,以此為例,就是在按下按鈕的時候會new一個Button出來,然後就會把它抓過去
public class MainActivity extends AppCompatActivity {
    Button pre,next;
    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pre=(Button)findViewById(R.id.pre);
        next=(Button)findViewById(R.id.next);
        img=(ImageView)findViewById(R.id.img);               
    }
    public void pre(View v){
 
}
public void next(View v){
}
 
4.用setImageResource()函式把照片放進來ex:img.setImageResource(R.drawable.img01);
public class MainActivity extends AppCompatActivity {
    Button pre,next;
    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pre=(Button)findViewById(R.id.pre);
        next=(Button)findViewById(R.id.next);
        img=(ImageView)findViewById(R.id.img);
 
    }
    int[] s={
    R.drawable.img01,
    R.drawable.img02,
    R.drawable.img03,
    R.drawable.img04,
    R.drawable.img05};
  
     int i=-1;
     public void pre(View v){
    i--;
    if(i<0){i=s.length-1;}
    img.setImageResource(s[i]);
 
}
public void next(View v){
        i++;
        if(i== s.length ){i=0;}
        img.setImageResource(s[i]);
 
}
}
**說明:
1. 用陣列設計可以點一按鈕就換到下一張圖的效果,兩個方法的變數要用同一個全域變數,因為照片是共用的
2.當i==s.length時就要從第一張照片開始,所以指定i=0
3.當i<0時,就要從最後一張照片開始,所以指定i=s.length-1
 
5.安裝桌面圖示,把要用的圖片放在mipmap資料夾下,再去修改manifests下的AndroidManifest.xml檔的
android:icon="@mipmap/logo",斜線後面的名稱即可
若是使用模擬器,要改
android:roundIcon="@mipmap/logo"
 
*程式參考(github):Change Image When Clicking Button
 
文章標籤
全站熱搜
創作者介紹
創作者 muchone 的頭像
muchone

簡單。生活。享受

muchone 發表在 痞客邦 留言(0) 人氣(999)