Create the Menu MenuItem dynamically Android example

public class MyActivity extends Activity {
//  http://www.apache.org/licenses/LICENSE-2.0
 
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(new SampleView(this));
		}
                    // set ID 
		    private static final int MY_MENU_1 = Menu.FIRST;
		    private static final int MY_MENU_2 = Menu.FIRST + 1;
		    private static final int MY_MENU_3 = Menu.FIRST + 2;
 
		    @Override
		    public boolean onCreateOptionsMenu(Menu menu) {
		        super.onCreateOptionsMenu(menu);
 
		        menu.add(0, MY_MENU_1, 0, "Hello").setShortcut('3', 'c');
		        menu.add(0, MY_MENU_2, 0, "About").setShortcut('4', 's');
		        menu.add(0, MY_MENU_3, 0, "Help").setShortcut('5', 'z');
		        return true;
		    }
 
		    @Override
		    public boolean onPrepareOptionsMenu(Menu menu) {
		        super.onPrepareOptionsMenu(menu);
		        return true;
		    }
 
		    @Override
		    public boolean onOptionsItemSelected(MenuItem item) {
 
		        switch (item.getItemId()) {
		            case MY_MENU_1:
		                Toast.makeText(getApplicationContext(), "Hello",
								Toast.LENGTH_LONG).show();
		            	//new ColorPickerDialog(this, this, mPaint.getColor()).show();
		                return true;
		            case MY_MENU_2:
 
		            	Toast.makeText(getApplicationContext(), item.getTitle(),
		            			Toast.LENGTH_LONG).show();
		            	return true;
		            case MY_MENU_3:
		            	Toast.makeText(getApplicationContext(), item.getTitle(),
		            			Toast.LENGTH_LONG).show();
		            	return true;
		        }
		        return super.onOptionsItemSelected(item);
		    }		
 
 
		private static class SampleView extends View {
 
			// CONSTRUCTOR
			public SampleView(Context context) {
				super(context);
				setFocusable(true);
 
			}
			@Override
			protected void onDraw(Canvas canvas) {
				Paint paint = new Paint();
 
				canvas.drawColor(Color.GREEN);
 
	            Bitmap b = Bitmap.createBitmap(200, 200, Bitmap.Config.ALPHA_8);
	             paint.setColor(Color.BLUE);
 
	            Shader mShader = new LinearGradient(0, 0, 100, 70, new int[] {
	                    Color.RED, Color.GREEN, Color.BLUE },
	                    null, Shader.TileMode.REPEAT); // CLAMP MIRROR REPEAT
	            Canvas c = new Canvas(b);
	            paint.setShader(mShader);
	            //c.drawCircle(60, 60, 30, paint);
	            c.drawRect(0, 0, 200, 200, paint);
	            canvas.drawBitmap(b, 10,10, paint);
			}
 
		}
	}
This entry was posted in Android Examples Code and tagged , , . Bookmark the permalink.


Comments are closed.



9,044 views