Convert view to bitmap on Android

here is my solution: public static Bitmap getBitmapFromView(View view) { //Define a bitmap with the same size as the view Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888); //Bind a canvas to it Canvas canvas = new Canvas(returnedBitmap); //Get the view’s background Drawable bgDrawable =view.getBackground(); if (bgDrawable!=null) //has background drawable, then draw it on the canvas bgDrawable.draw(canvas); else … Read more

setBackground vs setBackgroundDrawable (Android)

It’s deprecated but it still works so you could just use it. But if you want to be completly correct, just for the completeness of it… You’d do something like following: int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { setBackgroundDrawable(); } else { setBackground(); } For this to work you need to set buildTarget api … Read more

Set margins in a LinearLayout programmatically

Here is a little code to accomplish it: LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(30, 20, 30, 0); Button okButton=new Button(this); okButton.setText(“some text”); ll.addView(okButton, layoutParams);

Set the absolute position of a view

You can use RelativeLayout. Let’s say you wanted a 30×40 ImageView at position (50,60) inside your layout. Somewhere in your activity: // Some existing RelativeLayout from your layout xml RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout); ImageView iv = new ImageView(this); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30, 40); params.leftMargin = 50; params.topMargin = 60; rl.addView(iv, params); More examples: … Read more