There is a LinearLayout and some Buttons in my project. I want when each Button clicked add a small image to LinearLayout from drawable. How can I add a image to a LinearLayout programmatically?
This is my LinearLayout in a HorizontalScrollView:
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
>
<LinearLayout
android:id="#+id/LinearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
and here is my activity:
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout notes = (LinearLayout) findViewById(R.id.LinearLayout_notes);
final ImageView notes_do = new ImageView(this);
notes_do.setBackgroundResource(R.drawable.notes_do);
new Thread(new Runnable() {
#Override
public void run() {
final ImageButton img_1 = (ImageButton) findViewById(R.id.img_1_);
img_1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if( event.getAction() == MotionEvent.ACTION_DOWN ) {
notes.addView(notes_do);
}
return true;
}
}); // end of ontouch
}
}).start(); // end of thread
} // end of oncreate
}// end of activity
LinearLayout ll = (LinearLayout)findViewById(R.id.LinearLayout1);
for(int i=0;i<5;i++)
{
ImageView ii= new ImageView(this);
ii.setBackgroundResource(R.drawable.ic_action_search);
ll.addView(ii);
}
You can do a findViewById to the linearlayout and add an imageview to it dynamically in the onclicklistener of button
LinearLayout linLay = (LinearLayout)findViewById(R.id.LinearLayout1);
ImageView image = new ImageView(this);
//add image to imageview
...
linLay.addView(image);
ImageView img = new ImageView( this);
LinearLayout rl = (LinearLayout) findViewById(R.id.LinearLayout1);
LinearLayout.LayoutParams viewParamsCenter = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
img.setImageResource(R.drawable.ic_launcher);
img.setLayoutParams(viewParamsCenter);
rl.add(img);
As you want to set the image dynamically, on the button's click. you can add the image view to the linear layout
View LinearLayout1 = findViewById(R.id.Layout1);
ImageView image1 = new ImageView(getApplicationContext());
String uri = "#drawable/myresource.png"; // Here you can set the name of
// the image dynamically
int imageResource = getResources().getIdentifier(uri, null,
getPackageName());
Drawable res = getResources().getDrawable(imageResource);
image1.setImageDrawable(res);
((ViewGroup) LinearLayout1).addView(image1);
Related
I have a scrollable layout that shows images vertically :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".chatActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp">
<LinearLayout
android:id="#+id/imageGallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
</RelativeLayout>
This is how I generate the view in my code :
LinearLayout imageGallery;
File[] fList = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
imageGallery = (LinearLayout) findViewById(R.id.imageGallery);
addImagesToTheGallery();
}
private void addImagesToTheGallery() {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
fList = path.listFiles();
if(fList!=null)
{
int len = fList.length;
for(int i=0; i<len; i++)
{
imageGallery.addView(getImageView(i));
}
}
}
private View getImageView(int image) {
ImageView imageView = new ImageView(getApplicationContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 10, 0);
imageView.setLayoutParams(lp);
Bitmap bitmap = BitmapFactory.decodeFile(fList[image].getAbsolutePath());
imageView.setImageBitmap(bitmap);
return imageView;
}
Now, I want to add an onClick event for each of those images. When someone clicks on an image, I want to display some message specific to that image. So I should either be able to get the image or its position. How can I do that?
Set "imageView" onCLickListener.
private View getImageView(int image) {
ImageView imageView = new ImageView(getApplicationContext());
LinearLayout.LayoutParams lp = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 10, 0);
imageView.setLayoutParams(lp);
Bitmap bitmap = BitmapFactory.decodeFile(fList[image].getAbsolutePath());
imageView.setImageBitmap(bitmap);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO do something
Toast.makeText(this, "item num" +
image, Toast.LENGTH_LONG).show();
}
});
return imageView;
}
How to add view programmatically to existing view, for example I have textview in XML and now I need to add imageview below that textview programmatically, here is what I tried,
HorizontalScrollView scroll = new HorizontalScrollView(getApplicationContext());
LinearLayout imageLayout = new LinearLayout(getApplicationContext());
scroll.setLayoutParams(new ViewGroup.LayoutParams(imageLayout.getWidth(),
imageLayout.getHeight()));
scroll.addView(imageLayout);
for (int i = 0; i < 15; i++) {
final ImageView imageView = new ImageView(this);
imageView.setTag(i);
imageView.setImageResource(R.drawable.logo);
imageLayout.addView(imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("Tag", "" + imageView.getTag());
}
});
}but its not adding any imageview, I'm trying to do this in **AlertDialog**
ScrollView cannot have more than one child. You should wrap your layout inside of a LinearLayout and then after you can add any number of views into that LinearLayout. cheers :)
You are doing with wrong way.
Once check with below code snippet.
LinearLayout yourlayout = (LinearLayout)findViewById(R.id.layoutid);//Layout which is inside scrollview
LinearLayout imageLayout = new LinearLayout(getApplicationContext());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// add the rule that places your LinearLayout below your TextView object
params.addRule(RelativeLayout.BELOW, TextView.getId());
// set the layoutParams on the LinearLayout
imageLayout.setLayoutParams(params);
yourlayout.addView(imageLayout);
for (int i = 0; i < 15; i++) {
final ImageView imageView = new ImageView(this);
imageView.setTag(i);
imageView.setImageResource(R.drawable.logo);
imageLayout.addView(imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("Tag", "" + imageView.getTag());
}
});
}
I solved it by adding
<HorizontalScrollView
android:id="#+id/horizontal_scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/linear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
in XML
&
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
for (int i = 0; i < 10; i++) {
ImageView imageView = new ImageView(this);
imageView.setId(i);
imageView.setPadding(2, 2, 2, 2);
imageView.setImageBitmap(BitmapFactory.decodeResource(
getResources(), R.drawable.ic_launcher));
imageView.setScaleType(ScaleType.FIT_XY);
layout.addView(imageView);
}
in MainActivity.java
ImageView imageView = new ImageView(this.getActivity());
imageView.setId(View.generateViewId());
params.addRule(RelativeLayout.BELOW, imageView.getId());
I have a single image myimage.png which is placed in my res-drawable folder.
I have to create 50 ImageButtons in an activity all using this same image.
And then when a user clicks i need to pop out a toast saying button number i was clicked.
Here's what I have done:
public class AllImageButtons extends Activity {
int screendimesionx;
int screendimesiony;
ImageButton imageButton;
ImageButton allImageButtons[] = new ImageButton[50];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allbuttonimages);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
screendimesiony = metrics.heightPixels;
screendimesionx = metrics.widthPixels;
createButtonsAndAddListener();
}
public void createButtonsAndAddListener() {
for (int i = 0; i < 50; i++) {
imageButton = (ImageButton) findViewById(R.id.myimage);
float buttonimagey = imageButton.getDrawable().getBounds().height();
float buttonimagex = imageButton.getDrawable().getBounds().width();
float xspaceforeachbuttonimage = screendimesionx/50;
LayoutParams par = (LayoutParams)imageButton.getLayoutParams();
par.leftMargin = (int) (i*xspaceforeachbuttonimage);
par.topMargin = 0;
imageButton.setLayoutParams(par);
allImageButtons[i] = imageButton;
allImageButtons[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(AllbuttonimagesForSelectionActivity.this,
"ImageButton is clicked!", Toast.LENGTH_SHORT)
.show();
}
});
}
}}
and then there is the associated xml file allbuttonimages.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/myimage" />
</LinearLayout>
This xml layout displays only the last ImageButton from the loop.
My Question:
How can i dynamically create all 50 ImageButtons from the same image in a single view ?
You are not adding the buttons to the parent .
use addView(yourImageButton) to add your image button to activity
The button that is visible now is the one in xml
You should create new imageButton using new
eg: ImageButton imgBtn = new ImageButton(this)
Then set the properties and addView to your parent Layout
You will not get 50 buttons with the one defined in xml
You have one button in layout and you are calling findViewById for that.
You need to create new buttons each time and add it to the linearlayout.
public void createButtonsAndAddListener() {
for (int i = 0; i < 50; i++) {
imageButton = new ImageButton(this);
imageButton.setImageResource(R.drawable.myimage);
float buttonimagey = imageButton.getDrawable().getBounds().height();
float buttonimagex = imageButton.getDrawable().getBounds().width();
float xspaceforeachbuttonimage = screendimesionx/50;
LayoutParams par = (LayoutParams)imageButton.getLayoutParams();
par.leftMargin = (int) (i*xspaceforeachbuttonimage);
par.topMargin = 0;
imageButton.setLayoutParams(par);
allImageButtons[i] = imageButton;
allImageButtons[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(AllbuttonimagesForSelectionActivity.this,
"ImageButton is clicked!", Toast.LENGTH_SHORT)
.show();
}
});
((LinearLayout)findViewById(R.id.ll)).addView(imageButton);
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="#+id/ll">
</LinearLayout>
Your code wont add images to the layout. Get the parent layout in code and add images to it using addView. Between you do not need the image button in the xml. You can do some thing like this:
LinearLayout parent = (LinearLayout)findViewById(R.id.the_parent_layout);
for(int i = 0; i< 50; i++){
ImageButton image = new ImageButton(context);
//set whatever properties you want
//then add to the parent
parent.addView(image); // you can also specify the layout params here
}
Try This....
for (int i = 0; i < 50; i++) {
ImageButton b1 = new ImageButton(myrefmenu);
b1.setId(100 + i);
b1.setImageResource(R.drawable.imagename);
// b1.setText(adapt_objmenu.city_name_array[i]);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (i > 0) {
lp.addRule(RelativeLayout.RIGHT_OF, b1.getId() - 1);
}
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(AllbuttonimagesForSelectionActivity.this,
"ImageButton is clicked!", Toast.LENGTH_SHORT)
.show();
}
});
b1.setLayoutParams(lp);
relative.addView(b1);
}
I´m trying to include zooming in a Horizontal ScrollView. The idea is that the user touches the screen in the image he wants to highlight and that image get a little bit bigger than the others. I have make the Horizontall ScrollView but I´m having problems with the OnClick event. What is the better way to do it?
This is what I have in the MainActivity.java
public class Carrusel extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.iniciar);
{int[] images = new int[] { R.drawable.image1, R.drawable.image2,
R.drawable.image3, R.drawable.image4,
R.drawable.image5 };
LinearLayout sv = (LinearLayout) findViewById (R.id.carrusel);
for (int i=0 ; i<5; i++){
ImageView iv = new ImageView (this);
iv.setBackgroundResource (images[i]);
sv.addView(iv);
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.drawable.image1:
//I don´t know what to put here
break;
}
}
}
And here is what I have in te main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#color/black" >
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
>
<LinearLayout
android:id="#+id/carrusel"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
Here's how I'd do it:
MainActivity.java :
public class MainActivity extends Activity implements OnClickListener {
ImageView lastClicked = null;
int width = 400;
int height = 320;
int padding = 30;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout l;
l = (LinearLayout) findViewById(R.id.linear);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
width, height);
int[] images = new int[] { R.drawable.image1, R.drawable.image2,
R.drawable.image3, R.drawable.image4, R.drawable.image5 };
for (int i = 0; i < 5; i++) {
ImageView iv = new ImageView(this);
iv.setLayoutParams(layoutParams);
iv.setImageResource(images[i]);
iv.setPadding(padding, padding, padding, padding);
iv.setOnClickListener(this);
l.addView(iv);
}
}
#Override
public void onClick(View v) {
if (v instanceof ImageView) {
if (lastClicked != null) {
lastClicked.setPadding(padding, padding, padding, padding);
lastClicked.invalidate();
}
v.setPadding(0, 0, 0, 0);
v.invalidate();
lastClicked = (ImageView) v;
}
}
}
I'm basically trying to achieve drag&drop feature..
What i'm trying is that i provides sequence of images on the screen, if i click on any image available in images row that will be added to the Mains screen. But i'm getting problem that when i add new view into the Main Screen then all the other views also moved to top left corner.
Can you please tell me what is the problem...? Or kindly suggest me a tutorial or link where i can find solution.... or how to achieve this ?
I'm using Framelayout, So that i also achieve images overlapping...
This is the class in which all code is working:
public class drag extends Activity implements OnClickListener, OnTouchListener
{
ImageView img1;
Button btn,btn2;
FrameLayout layout;
LayoutParams params;
ImageView im , im2, im3 ,im4;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layout = (FrameLayout) findViewById(R.id.vg);
layout.setDrawingCacheEnabled(true);
im = (ImageView)findViewById(R.id.img1);
im.setDrawingCacheEnabled(true);
im.setOnTouchListener(this);
im.setOnClickListener(this);
btn = (Button)findViewById(R.id.btn1);
btn.setDrawingCacheEnabled(true);
btn.setOnClickListener(this);
btn.setOnTouchListener(this);
btn2 = (Button)findViewById(R.id.btn2);
btn2.setDrawingCacheEnabled(true);
btn2.setOnClickListener(this);
btn2.setOnTouchListener(this);
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
im2 = new ImageView(drag.this);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
im2.setImageBitmap(bm);
im2.setOnTouchListener(drag.this);
im2.setOnClickListener(drag.this);
layout.addView(im2, params);
}
});
btn2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
saveImage(bm);
}
});
}
public void saveImage(Bitmap myBitmap)
{
MediaStore.Images.Media.insertImage(getContentResolver(), myBitmap, "mmsImage" , "mmsimage");
}
int l, t, r, b;
int oldLeft, oldTop;
PointF p, curr;
#Override
public boolean onTouch(View view, MotionEvent me)
{
if (me.getAction() == MotionEvent.ACTION_DOWN)
{
//status = START_DRAGGING;
Log.i("status"," AAA dOWN");
img1 = new ImageView(this);
view.setDrawingCacheEnabled(true);
Bitmap mmsImage = Bitmap.createBitmap(view.getDrawingCache());
img1.setImageBitmap(mmsImage);
img1.setOnTouchListener(drag.this);
img1.setOnClickListener(drag.this);
oldLeft = (int)view.getLeft();
oldTop = (int)view.getTop();
p = new PointF(me.getRawX(), me.getRawY());
}
if (me.getAction() == MotionEvent.ACTION_MOVE)
{
Log.i("status"," AAA draging");
int xDiff = (int)(me.getRawX() - p.x);
int yDiff = (int)(me.getRawY() - p.y);
p.x = me.getRawX();
p.y = me.getRawY();
l = view.getLeft();
t = view.getTop();
r = view.getRight();
b = view.getBottom();
view.layout(l + xDiff, t + yDiff , r + xDiff, b + yDiff);
}
if (me.getAction() == MotionEvent.ACTION_UP)
{
Log.i("status"," AAA UP");
//captureUserMove(view);
}
return false;
}
}
Here is the XML :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/vg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/white" >
<ImageView
android:id="#+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/ic_launcher" />
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</FrameLayout>
You set params, but don't specify how to position the added view. Try this:
In onCreate()
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.LEFT | Gravity.TOP; // you need this for margins to work
In the click listener:
// your x and y where you want the new view
params.leftMargin = x;
params.topMargin = y;
Putting
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
inside
#Override
public void onClick(View v)
{
}
will work.