Java (Android): ボタンのクリックと反応

device-2013-01-03-000409

java: ClickTestActivity.java

package jp.feb19.snippets;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class ClickTestActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);
		
		// Button に反応する画像
		final ImageView image = new ImageView(this);
		image.setImageResource(R.drawable.sample);
		layout.addView(image, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		
		// Button を設置
		final Button button = new Button(this);
		button.setText("画像を非表示");
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (image.getVisibility() == View.INVISIBLE) {
					image.setVisibility(View.VISIBLE);
					button.setText("画像を非表示");
				} else {
					image.setVisibility(View.INVISIBLE);
					button.setText("画像を表示");
				}
			}
		});
		layout.addView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		
		setContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}
}