import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.view.Gravity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private static final int REQUEST_CODE = 1; //非负 private ImageView iv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout mLinearLayout = new LinearLayout(this); mLinearLayout.setBackgroundColor(Color.RED); // 设置背景颜色 mLinearLayout.setOrientation(LinearLayout.VERTICAL); // 垂直布局 TextView tv = new TextView(this); tv.setText("哈哈,原来可以不用XML啊,点下那个按钮吧,帅哥"); Button mButton = new Button(this); mButton.setText("另外一个世界"); mButton.setGravity(Gravity.CENTER); iv = new ImageView(this); mButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, REQUEST_CODE); } }); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); mLinearLayout.addView(tv, params); mLinearLayout.addView(mButton,params); mLinearLayout.addView(iv,params); setContentView(mLinearLayout); } /* (non-Javadoc) * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(data != null && data.getExtras() != null) { Bitmap bitMap = (Bitmap)data.getExtras().get("data"); iv.setImageBitmap(bitMap); Toast.makeText(this, "bmp.height:" + bitMap.getHeight() + ",bmp.width:" + bitMap.getWidth(), Toast.LENGTH_LONG).show(); Toast.makeText(this, "requestCode:" + requestCode + ",resultCode" + resultCode, Toast.LENGTH_LONG).show(); } super.onActivityResult(requestCode, resultCode, data); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }