2016年6月19日 星期日

第一隻Andorid

設定 Linear Layout 方向為垂直 設定物件的擺放為 置中
 
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:gravity="center"
    android:orientation="vertical"
    tools:context="com.example.test.MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="328dp"
        android:layout_height="392dp"
        android:layout_margin="10sp"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10sp"
        android:layout_weight="0.16"
        android:src="@drawable/madoka" />

    <Button
        android:id="@+id/changeImge1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/changeImg" />

</LinearLayout>

建立自定意圖片res  的 drawable 資料夾放置圖片。

撰寫程式

imgview.getDrawable().getConstantState() == 取得目前這個畫面的圖片格式判斷現在的圖片。

public class MainActivity extends Activity {
 Button changeImgbutton;
 ImageView  imgview;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  changeImgbutton =  (Button)findViewById(R.id.changeImge1);
  imgview = (ImageView)findViewById(R.id.imageView1);
  changeImgbutton.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    if(imgview.getDrawable().getConstantState().equals(getResources().getDrawable(R.drawable.madoka,getApplicationContext().getTheme()).getConstantState())){
     imgview.setImageResource(R.drawable.i55963);
    }else{
     imgview.setImageResource(R.drawable.madoka);
    }
   }
  } );
 }