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);
}
Related
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 am trying to make a game where in the start menu, when a button is clicked, a story event will be happening. There will be different stories when the button is clicked depending on the character the player is using,so I don't want to make a billion different activities/fragments for the stories.
I have two layouts that I want to switch within the same activity.
To switch from layout 1 to layout 2, I tried to add layout 2 to layout 1, and also tried ViewFlipper , but when I try to switch from Layout 1 to layout 2, the TextView in layout 2 says "New text" first before turning into what I want it to say. The textbox, which is supposed to be at the bottom, appears at the top first and then jumps to the bottom
I've also tried using threads to have layout 2 preload but that just messes up layout 2. So what should I do?
Here is my class for the story
public class Story extends FrameLayout {
String[][] story;
int H;
int W;
int L;
int index =0;
TextView text;
ImageView character;
View v;
Story(Context context,String[][]story,int length){
super(context);
this.story=story;
this.L = length;
init(context);
}
public void init(Context context) {
LayoutInflater l = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = l.inflate(R.layout.story, this, true);
final RelativeLayout.LayoutParams textParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final FrameLayout.LayoutParams imageParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
text = (TextView) v.findViewById(R.id.story);
character = (ImageView) v.findViewById(R.id.chara);
final RelativeLayout textBox = (RelativeLayout) v.findViewById(R.id.textbox);
textBox.post(new Runnable() {
#Override
public void run() {
H = textBox.getHeight();
W = textBox.getWidth();
textParams.setMargins(W / 12, H / 8, W / 10, H / 8);
text.setLayoutParams(textParams);
text.setText(story[index][0]);
}
});
v.post(new Runnable() {
#Override
public void run() {
int h = v.getHeight();
imageParams.setMargins(W / 7 * 2, h / 10, 0, H / 3);
character.setLayoutParams(imageParams);
character.setImageResource(Integer.parseInt(story[index][1]));
}
});
}
}
XML for the story
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chara"
android:scaleType="fitStart"
android:adjustViewBounds="true"
/>
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textbox"
android:layout_gravity="bottom">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/vntextbox"
android:adjustViewBounds="true"
android:scaleType="fitEnd">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/story" />
</RelativeLayout>
</merge>
For each character, they have a method that returns their story, eg for a particular character :
public class Player extends ImageView {
Context context;
Player (Context context){
super(context);
this.context=context;
}
public Story getIntro(){
int normal = R.drawable.normal;
int serious = R.drawable.serious;
int happy = R.drawable.happy;
final int length = 8;
String[][] story = // a story
final Story s = new Story(context, story, l);
s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do some stuff
}
});
return s;
}
}
And here is where the story is used
public class StartMenu extends AppCompatActivity {
#Override
protected void onCreate(final Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.startmenu);
final RelativeLayout r = (RelativeLayout)findViewById(R.id.startscreen);
final Button b =new Button(this);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here I want to do something like this: (doesn't work due to problems described above)
Player p = new Player(StartMenu.this);
Story s = p.getIntro();
r.removeAllViews();
r.addView(s);
}
});
Try to leave the text space empty on your .xml and just fill it when you're creating the activity (if it is dynamic). It will solve the text change flick.
About the two layouts, search about Fragments.
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 want to create several ImageButtons programmatically. I am able to create them but the click event listener keeps receiving the same view (Button 2), whether I click on button 0 ,button1 or button 2.
RelativeLayout gameBoard = (RelativeLayout) findViewById(R.id.RelGameboard);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT,1);
for(int i = 0 ; i < 3 ; i++)
{
ImageButton btnGreen = new ImageButton(this);
btnGreen.setImageResource(R.drawable.bola_verde);
btnGreen.setLayoutParams(lp);
btnGreen.setOnClickListener(mGreenBallOnClickListener);
btnGreen.setBackgroundColor(Color.TRANSPARENT);
btnGreen.setTag(i);
btnGreen.setId(i);
gameBoard.addView(btnGreen);
}'
Click event listener:
private View.OnClickListener mGreenBallOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
//check which green ball was clicked
ImageButton imgBtn = (ImageButton) v;
Log.i("greeny","Clicked on green ball->"+imgBtn.getTag()+" v.ID->"+v.getId());
}
};
For any imagebutton drawn, when I click I get : Clicked on green ball->2 v.ID->2
The buttons are in different positions ( i set a different padding for each one of them but in order to simplify the code I didn't put it here )
Try adding a onClickListener -
private View.OnClickListener ClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int selected_item = (Integer) v.getTag();
}
};
EDIT
Try creating a array of ImageButtons -
ImageButton[] btnGreen = new ImageButton[3];
for (int i = 0; i < 3; i++) {
btnGreen[i] = new ImageButton(this);
btnGreen[i].setImageResource(R.drawable.bola_verde);
btnGreen[i].setLayoutParams(lp);
btnGreen[i].setOnClickListener(ClickListener);
btnGreen[i].setBackgroundColor(Color.TRANSPARENT);
btnGreen[i].setTag(i);
btnGreen[i].setId(i);
gameBoard.addView(btnGreen[i]);
}
This happen because you do not set layout of button, All button in same place.
Use Aboveof,Belowof,left,right,center
Example
params.addRule(RelativeLayout.ALIGN_PARENT_ABOVE);
relativeLayout.addView(button, params);
Try this code:
RelativeLayout gameBoard = (RelativeLayout)findViewById(R.id.RelGameboard);
ImageButton[] imageButtons;
private final int NUMBER_OF_IMAGE_BUTTONS = 5; //your number of image buttons
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT,1);
imageButtons = new ImageButton[NUMBER_OF_IMAGE_BUTTONS];
for(int i = 0 ; i < NUMBER_OF_IMAGE_BUTTONS; i++){
imageButtons[i] = new ImageButton(this);
imageButtons[i].setImageResource(R.drawable.bola_verde);
imageButtons[i].setLayoutParams(lp);
imageButtons[i].setOnClickListener(mGreenBallOnClickListener);
imageButtons[i].setBackgroundColor(Color.TRANSPARENT);
imageButtons[i].setTag(i);
imageButtons[i].setId(i);
gameBoard.addView(imageButtons[i]);
}
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.