我們預設放一張紅色的花到ImageView,
當按下按鈕,即切換到藍色的花
1.加入Images到res/drawable-hdpi
2.加入ImageView及一個按鈕
res/layout/activity_main.xml
<RelativeLayout 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" tools:context=".MainActivity" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="flower1" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/button1" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_marginBottom="17dp" android:src="@drawable/flower2" /> </RelativeLayout>
3. MainActivity.java
import android.os.Bundle; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { Button button; ImageView image; boolean flowerImgShowed = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addListenButton(); } public void addListenButton() { image = (ImageView) findViewById(R.id.imageView1); button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // 按下按鈕,來切換圖片 if (!flowerImgShowed) { image.setImageResource(R.drawable.flower1); button.setText("Flower2); flowerImgShowed = true; } else { image.setImageResource(R.drawable.flower2); button.setText("Flower1"); flowerImgShowed = false; } } }); } }結果:
沒有留言:
張貼留言