/*
* 访问Drawable资源的宽和高
* 程序通过Bitmap对象的BitmapFactoryResource()方法来取得Import和
* Drawable的图片文件,在通过Bitmap的对象的getHeight()和getWidth()
* 取得Drawable的宽高。
*/
import 略;
public class Ex07_01Activity extends Activity {
private TextView mTextView;
private ImageView mImageView;
protected static final int CONTEXT_ITEM1 = Menu.FIRST;
protected static final int CONTEXT_ITEM2 = Menu.FIRST + 1;
protected static final int CONTEXT_ITEM3 = Menu.FIRST + 2;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.myTextView1);
mImageView = (ImageView) findViewById(R.id.myImageView1);
mImageView
.setImageDrawable(getResources().getDrawable(R.drawable.baby));
mImageView
.setOnCreateContextMenuListener(new ListView.OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
menu.add(Menu.NONE, CONTEXT_ITEM1, 0,
R.string.str_context1);
menu.add(Menu.NONE, CONTEXT_ITEM2, 0,
R.string.str_context2);
menu.add(Menu.NONE, CONTEXT_ITEM3, 0,
R.string.str_context3);
}
});
}
// 重写OnContextItemSeldcted来定义用户单击后的动作
public boolean onContextItemSelected(MenuItem item) {
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.baby);
int intHeight = myBitmap.getHeight();
int intWidth = myBitmap.getWidth();
try {
switch (item.getItemId()) {
case CONTEXT_ITEM1:
String strOpt = getResources().getString(R.string.str_width)
+ "=" + Integer.toString(intWidth);
mTextView.setText(strOpt);
break;
case CONTEXT_ITEM2:
String strOpt2 = getResources().getString(R.string.str_height)
+ "=" + Integer.toString(intHeight);
mTextView.setText(strOpt2);
break;
case CONTEXT_ITEM3:
String strOpt3 = getResources().getString(R.string.str_width)
+ "=" + Integer.toString(intWidth) + "\n"
+ getResources().getString(R.string.str_height) + "="
+ Integer.toString(intHeight);
mTextView.setText(strOpt3);
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return super.onContextItemSelected(item);
}
}
布局文件很简单,在这里我就不再详述了,下面我们来看看程序的运行结果: