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;
}
}
}
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;
}
I am trying to scroll item to the middle position of the screen after selecting it.I have used Horizontalscrollview and LinearLayout inside it to add item. I show in the XML
XML
<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:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/bottom"
android:orientation="vertical" >
<HorizontalScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/updown"
android:layout_weight="0.8"
android:fadingEdgeLength="0dp" >
<LinearLayout
android:id="#+id/horizontalbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/tlbackground"
android:baselineAligned="true"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</RelativeLayout>
Class
public class MainActivity extends FragmentActivity implements ActionBar.TabListener
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hsl = (HorizontalScrollView) findViewById(R.id.scrollView);
LinearLayout l1 = (LinearLayout)findViewById(R.id.horizontalbar);
for(int i = 0; i < 20; i++)
{
Button b = new Button(this);
b.setText("t"+i);
ll.addView(b);
}
}
}
I want something like in figure
before click
after click
How can I Scroll that selected item to the middle in HorizontalScrollview?
After long try , I have got it with this
for (int i = 0; i < 20; i++) {
final Button b = new Button(this);
b.setText("t" + i);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int scrollX = (b.getLeft() - (screenWidth / 2)) + (b.getWidth() / 2);
hsl.smoothScrollTo(scrollX, 0);
}
});
ll.addView(b);
}
This is how your onCreate should look like:
hsl = (HorizontalScrollView) findViewById(R.id.scrollView);
LinearLayout ll = (LinearLayout) findViewById(R.id.horizontalbar);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
final int width = size.x;
for (int i = 0; i < 20; i++) {
final Button b = new Button(this);
b.setText("t" + i);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int center = (width - b.getWidth())/2;
hsl.scrollTo(b.getLeft() - center, b.getTop());
}
});
ll.addView(b);
}
The only thing i didn't discover is why i need to substract additional 200px (in my case). Probably some padding or something else. Instead of 200, you could discover how many dips is it and call function:
public static int convertDipToPixels(Context c, float dips) {
return (int) (dips * c.getResources().getDisplayMetrics().density + 0.5f);
}
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);
}
If I want to add a button in this class so that I can call the onclicklistener, how should I do it?
public class GameView extends View {
Path circle;
Paint cPaint;
Paint tPaint;
String z;
int i = 65, strt, arc, leftx, topy, rightx, bottomy, maxx, maxy;
boolean flag1, flag2, flag3;
double n1, n2;
int n, n3 = 180,n4,n5 = 90;
float f1 = 180, f2 = 90;
Button b1;
Random r = new Random();
RectF oval;
public GameView(Context context) {
super(context);
leftx = 0;
topy = 60;
rightx = 150;
bottomy = 120;
z = String.valueOf(Character.toChars(i));
cPaint = new Paint();
cPaint.setColor(Color.RED);
strt = 45;
arc = 315;
n1 = Math.random() * 600;
Log.d("random", z);
if (flag2 == false)
new DrawThread(this);
// cPaint.setStrokeWidth(2);
tPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
tPaint.setStyle(Paint.Style.FILL_AND_STROKE);
tPaint.setColor(Color.BLACK);
float scale = getResources().getDisplayMetrics().scaledDensity;
tPaint.setTextSize(20 * scale);
}
public void onSizeChanged(int w,int h,int oldh,int oldw) {
maxx = oldw;
maxy = oldh;
}
//#Override
protected void onDraw(Canvas canvas) {
// Drawing commands go here
oval = new RectF(leftx,topy,rightx,bottomy);
canvas.drawArc(oval, strt, arc, true, cPaint);
while (i < 90) {
canvas.drawText(String.valueOf(Character.toChars(i)),f1,f2, tPaint);
break;
}
}
}
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative_layout);
add the above below setContentView
setContentView(R.layout.activity_new_game);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative_layout);
You need to set the layout using setContentView and then initialize views.
Note you can findViewById of the current view hierarchy set to the activity
Edit:
Example: This is an example. I don't see why it won't work if you do similar as below.
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".NewGame"
android:id="#+id/relative_layout"
>
<Button
android:id="#+id/prev_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/next_button"
android:layout_alignBottom="#+id/next_button"
android:layout_centerHorizontal="true"
android:text="stop_label" />
<Button
android:id="#+id/next_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/prev_button"
android:text="start_label" />
<RelativeLayout
android:layout_width="wrap_content"
android:id="#+id/rl"
android:layout_below="#+id/prev_button"
android:layout_height="wrap_content"
>
</RelativeLayout>
</RelativeLayout>
Activity
public class MainActivity extends Activity {
private Button btn1;
private EditText edt1, edt2, edt3, edt4 ,edt5, edt6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyView mv = new MyView(this);
setContentView(R.layout.activity_main);
RelativeLayout layout= (RelativeLayout) findViewById(R.id.rl);
layout.addView(mv);
}
class MyView extends View
{
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawColor(Color.RED);
}
}
}
snapshot
You need to inflate your view before trying to find your relative layout. Try :
RelativeLayout layout;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
gameview=new GameView(this);
setContentView(R.layout.activity_new_game);
layout = (RelativeLayout) findViewById(R.id.relative_layout);
//LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//view = mInflater.inflate(R.layout.activity_new_game, gameview, true);
layout.addView(gameview);
}
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative_layout);
you can't call findViewById before setContentView. Move
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative_layout);
after setContentView(R.layout.activity_new_game);
you didn't initialize layout in your code so First initialize layout after setContentView then add view to your layout
RelativeLayout layout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_game);
//Initialize game view
GameView gameview=new GameView(this);
//initialize layout
layout = (RelativeLayout) findViewById(R.id.relative_layout);
//adding game view to layout
layout.addView(gameview);
}
Edit:
initializing like this before setContentView
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative_layout);
is wrong approach you must initialize views only after setContentView like the above code
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.