I am making a number of imageViews programmatically in a loop and assigning them ids. But when in onClick method I need to get the id of images, it is returning the id of the last image only. How do I get the id of the image that is clicked?
The code I am using:
for (int j = 0; j < 5; j++) {
TableRow tr = new TableRow(this);
imageUrl = "http://ondamove.it/English/images/users/";
imageUrl = imageUrl + listObject.get(j).getImage();
image = new ImageView(this);
image.setPadding(20, 10, 0, 0);
image.setId(j+1);
tr.addView(image);
try {
new DownloadFileAsync(image, new URL(imageUrl))
.execute(imageUrl);
images.add(image);
//images = new ImageView[5];
}
catch (Exception e) {
e.printStackTrace();
}
tr.addView(image);
table.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
image.setOnClickListener(clickImageListener);
Following is the onclicklistener.
private OnClickListener clickImageListener = new OnClickListener() {
public void onClick(View v) {
imageId = image.getId();
Intent fullScreenIntent = new Intent(v.getContext(),FullImageActivity.class);
fullScreenIntent.putExtra(ProfilePageNormalUser.class.getName(),imageId);
ProfilePageNormalUser.this.startActivity(fullScreenIntent);
}
};
Inside the onClick(View v) method you can call v.getId() - this will return you the ID of the View being clicked. Hope this helps.
Try this out:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int index = 0;
for (int i = 0; i < image.length; i++)
{
if (image[i].getId() == v.getId())
{
index = i;
break;
}
}
Toast.makeText(this, "Image clicked index => "+index, Toast.LENGTH_SHORT).show();
}
Related
I created image view programatically, and need check image view is empty or not.
getdrawable(),getHeigt() and getwidth() methodes but it is not working for me.
Imageview created like this:
ImageView iv = new ImageView(this);
code:
public void dynamicTable(String alist[]) throws NullPointerException {
try {
TableLayout tl = (TableLayout) findViewById(R.id.main_table1);
tl.setBackgroundColor(Color.GRAY);
sizelen = alist.length;
cam = new Button[sizelen];
iv = new ImageView[sizelen];
int k;
for (k = 0; k < sizelen; k++) {
try {
final int j = k;
TableRow tr_head = new TableRow(this);
TableLayout.LayoutParams rowparams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
int leftMargin = 2;
int topMargin = 1;
int rightMargin = 2;
int bottomMargin = 1;
rowparams.setMargins(leftMargin, topMargin, rightMargin,
bottomMargin);
rowparams.weight = (float) 0.5;
tr_head.setLayoutParams(rowparams);
// tr_head.setId(10);
tr_head.setBackgroundColor(Color.WHITE);
/*
* tr_head.setLayoutParams(new LayoutParams(
* LayoutParams.FILL_PARENT LayoutParams.WRAP_CONTENT));
*/
cam[k] = new Button(this);
cam[k].setText(alist[k]);
cam[k].setTextColor(Color.WHITE);
cam[k].setBackgroundColor(Color.parseColor("#ffab00"));
cam[k].setClickable(true);
cam[k].setFocusable(true);
cam[k].setGravity(Gravity.LEFT);
cam[k].setMaxLines(2);
cam[k].setPadding(10, 10, -10, 10);
cam[k].setAllCaps(false);
cam[k].setTextSize(13);
cam[k].setLayoutParams(new TableRow.LayoutParams(85,
TableLayout.LayoutParams.WRAP_CONTENT));
// cam[i].setWidth(150);
// cam[i].setEms(0);
// cam[i].setGravity(25);
// cam[i](Gravity.LEFT);
// cam[i].setLayoutParams(params);
cam[k].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cam[j].setBackgroundColor(Color.GRAY);
camera(j);
}
});
tr_head.addView(cam[k]); // add the column to the table row
// here
iv[k] = new ImageView(this);
iv[k].setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
iv[k].setPadding(0, 7, 10, 0);
iv[k].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imageviewOnclick(iv[j]);
}
});
tr_head.addView(iv[k]); // dd the column to the table row
// here
tl.addView(tr_head, rowparams);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
These methods will take the photo from the phone and display it in an ImageView, i guess you can use this in your code to see if the photo shows up or not.
public void DisplayPhotoPreview(){
DisplayPhotoPreview = (Button)findViewById(R.id.UploadPhotoPreviewBtn);//Finds the button in design and put it into a button variable.
DisplayPhotoPreview.setOnClickListener(//Listens for a button click.
new View.OnClickListener() {//Creates a new click listener.
#Override
public void onClick(View v) {//does what ever code is in here when the button is clicked
switch (v.getId()) {//switches to the case if that .id. is clicked.
case R.id.UploadPhotoPreviewBtn://Does what ever the code is in the case if the upload button is clicked.
//I open up an intent variable and through different commands and I open up my gallery on my phone and i cant get
//out of the gallery until i choose a photo. Then I save the photo in the intent and call the onActivityResult() method which displays the image.
//Also a intent is how two activities can send data.
Intent ChoosePhotoFromGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(ChoosePhotoFromGallery, RESULT_LOAD_IMAGE);//Stores the image into the variable.
break;
}
}
}
);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//so the if statement checks if the image came through, double checks if the result is okay and triple checks to see if the data is not null.
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null){
//gets the address of the image/data !!!!!!ALSO CAN HOLD THE ADDRESS FOR THE SERVER!!!!!!.
Uri Image = data.getData();
ItemPhotoPreview = (ImageView)findViewById(R.id.ItemPhotoPreviewImageView);
//Sets the image into the variable and displays it
ItemPhotoPreview.setImageURI(Image);
}
}
<string name="Manuf0">best</string>
<string name="Manuf1">Bravo</string>
<string name="Manuf2">zoo</string>
<string name="Manuf3">Skitz</string>
<string name="Manuf4">don</string>
<string name="Manuf5">animal</string>
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scrollviewManuf = new ScrollView(this);
LinearLayout linearlayout = new LinearLayout(this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
scrollviewManuf.addView(linearlayout);
for (int i = 0; i < 5; i++)
{
LinearLayout linearManuf = new LinearLayout(this);
linearManuf.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linearManuf);
Manufb = new Button(this);
int id = getResources().getIdentifier("Manuf" + i, "string", getPackageName());
String Manuf = getResources().getString(id);
Manufb.setText(Manuf);
Manufb.setId(i);
Manufb.setTextSize(30);
Manufb.setPadding(0, 0, 0, 0);
// b.setTypeface(Typeface.SERIF,Typeface.ITALIC);
Manufb.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
linearManuf.addView(Manufb);
Manufb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String SManuf= Manuf.replaceAll("&","").replaceAll(" ","").replaceAll("/","").replaceAll(" / ","").replaceAll("/ ","").replaceAll(" /","".replaceAll("&",""));
//Panel= getResources().getString(id);
Toast.makeText(getApplicationContext(), SManuf , Toast.LENGTH_SHORT).show();
Intent passIntent = new Intent(Manufacturers.this,panels.class);
passIntent.putExtra("SManuf",SManuf);
startActivity(passIntent);
}
});
}
this.setContentView(scrollviewManuf);
}
}
How do I sort the buttons generated from the following code alphabetically base on string values.
Currently they are listed as the buttons are produced 0 through to 5.
The list is in an xml string file, want to eb alphabetical so I can just add more to the file as needs be, and the programming just sort it alphabetically which suits me.
Not been able to find anything yet , but I am gueesing I may need to define the list in the file and sort that list can anyone point me in the right direction please.
Okay, so I can see the code is doing something but the sort order isn't changing and the String s is showing up in intellij as not used, : new code below:-
marked the sections with // here
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> theStrings = new ArrayList<>();//Here
scrollviewManuf = new ScrollView(this);
LinearLayout linearlayout = new LinearLayout(this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
scrollviewManuf.addView(linearlayout);
for (int i = 0; i < 28; i++) {
LinearLayout linearManuf = new LinearLayout(this);
linearManuf.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linearManuf);
Manufb = new Button(this);
int id = getResources().getIdentifier("Manuf" + i, "string", getPackageName());
String Manuf = getResources().getString(id);
theStrings.add(Manuf); /// Here
Manufb.setText(Manuf);
Manufb.setId(i);
Manufb.setTextSize(30);
Manufb.setPadding(0, 0, 0, 0);
// b.setTypeface(Typeface.SERIF,Typeface.ITALIC);
Manufb.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
linearManuf.addView(Manufb);
Manufb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String PManuf =Manuf;
// TODO Auto-generated method stub
String SManuf= Manuf.replaceAll("&","").replaceAll(" ","").replaceAll("/","").replaceAll(" / ","").replaceAll("/ ","").replaceAll(" /","".replaceAll("&",""));
//Panel= getResources().getString(id);
Toast.makeText(getApplicationContext(), Manuf+" Selected" , Toast.LENGTH_SHORT).show();
Intent passIntent = new Intent(Manufacturers.this,panels.class);
passIntent.putExtra("SManuf",SManuf);
passIntent.putExtra("PManuf",PManuf);
startActivity(passIntent);
}
} );
} Collections.sort(theStrings); //here
for (String s : theStrings) { //here
//...
this.setContentView(scrollviewManuf); }//here
}
}
The following code is looping each time it loops its adding an extra repeated option.
ie. Cat,dog,mouse, donkey correct list is the list but I am getting, Cat, dog.dog, mouse,mouse,mouse, donkey, donkey, donkey,donkey but still no sorting, still working on it but here is the code.
ArrayList<String> theStrings = new ArrayList<>();
for (int i = 0; i < 28; i++) {
int id = getResources().getIdentifier("Manuf" + i, "string", getPackageName());
String Manuf = getResources().getString(id);
theStrings.add(Manuf);
Collections.sort(theStrings);
for (String s : theStrings) {
LinearLayout linearManuf = new LinearLayout(this);
linearManuf.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linearManuf);
Manufb = new Button(this);
Manufb.setText(Manuf);
Manufb.setId(i);
Manufb.setTextSize(30);
Manufb.setPadding(0, 0, 0, 0);
// b.setTypeface(Typeface.SERIF,Typeface.ITALIC);
Manufb.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
linearManuf.addView(Manufb);
Manufb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String PManuf = Manuf;
// TODO Auto-generated method stub
String SManuf = Manuf.replaceAll("&", "").replaceAll(" ", "").replaceAll("/", "").replaceAll(" / ", "").replaceAll("/ ", "").replaceAll(" /", "".replaceAll("&", ""));
//Panel= getResources().getString(id);
Toast.makeText(getApplicationContext(), Manuf + " Selected", Toast.LENGTH_SHORT).show();
Intent passIntent = new Intent(Manufacturers.this, panels.class);
passIntent.putExtra("SManuf", SManuf);
passIntent.putExtra("PManuf", PManuf);
startActivity(passIntent);
}
});
}
}
this.setContentView(scrollviewManuf);
}
}
Read it into a list, sort it and loop over it:
ArrayList<String> theStrings = new ArrayList<>();
for (int i = 0; i < 28; i++) {
int id = getResources().getIdentifier("Manuf" + i, "string", getPackageName());
String Manuf = getResources().getString(id);
theStrings.add(Manuf);
}
Collections.sort(theStrings);
for (String s : theStrings) {
LinearLayout linearManuf = new LinearLayout(this);
linearManuf.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linearManuf);
Manufb = new Button(this);
Manufb.setText(s); // <-- use the String here
Manufb.setId(i);
Manufb.setTextSize(30);
Manufb.setPadding(0, 0, 0, 0);
// b.setTypeface(Typeface.SERIF,Typeface.ITALIC);
Manufb.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
linearManuf.addView(Manufb);
...
I have created a screen in which have created RelativeLayout dynamically. After that I have added some ImageView under RelativeLayout.
The requirement is that when I click on any Image View then that ImageView should be zoom by 20% and other images show be adjusted automatically.
So I have two problems:
How to zoom a particular ImageView (other ImagesView should be zoom out if already zoomed in)
How to adjust other Image View when perform zoom in and zoom out
Please suggest, I have not worked on Animation before.
Here is code to create layout dynamically:
// Method for adding layout and images
private void addRow(List<HashMap<String, String>> list) {
int breaker = 4, j, row = 0, tempSize = 0;
// Getting number of rows to create
row = (drinkList.size() % 5) == 0 ? drinkList.size() / 5 : (drinkList.size() / 5) + 1;
// Looping for rows
for (j = 0; j < row; j++) {
// Specifying breaker value to break the images row
if (j % 2 != 0) {
breaker = 4;
} else {
breaker = 5;
}
// Creating layout for rows
RelativeLayout layout = new RelativeLayout(Drinks.this);
layout.setId(111 + j);
// Setting layout parameters to row layout
// layout.setLayoutParams(new
// LayoutParams(LayoutParams.WRAP_CONTENT,
// LayoutParams.WRAP_CONTENT, Gravity.CENTER));
RelativeLayout.LayoutParams newParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
if (j > 0) {
newParams.addRule(RelativeLayout.BELOW, (111 + j) - 1);
}
layout.setLayoutParams(newParams);
int c = 0;
tempSize = list.size();
// Looping for placing Images
while (tempSize != 0 && c < breaker) {
// getting hash map from list
HashMap<String, String> h = new HashMap<String, String>();
h = list.get(0);
// Creating Image
final ImageView imageView = new ImageView(Drinks.this);
// Layout Parameters for Image
LayoutParams lpImage = new LayoutParams(150, 150);
imageView.setId(111 + c);
if (c > 0) {
lpImage.addRule(RelativeLayout.RIGHT_OF, (111 + c) - 1);
}
imageView.setTag(c);
lpImage.setMargins(10, 10, 10, 10);
imageView.setLayoutParams(lpImage);
URI uri = null;
URL imageUrl;
String brandID, categoryID, flavourID;
try {
imageUrl = new URL(h.get(Utility.KEY_ICON).toString().replace(" ", "%20"));
brandID = h.get(Utility.KEY_BRAND_ID);
categoryID = h.get(Utility.KEY_CATEGORY_ID);
flavourID = h.get(Utility.KEY_FLAVOUR_ID);
// HashMap<String, String> hash = new HashMap<String,
// String>();
// hash.put(Utility.KEY_BRAND_ID, brandID);
// hash.put(Utility.KEY_CATEGORY_ID, categoryID);
// Setting tag
imageView.setTag(brandID);
uri = new URI(imageUrl.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Loading image from URLs
ImageLoader imageLoader = new ImageLoader(Drinks.this);
imageLoader.DisplayImage(uri.toString(), R.drawable.ic_launcher, imageView);
/**
* Click Listener of Image
* **/
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(Drinks.this, "TAG " + imageView.getTag(), 2000).show();
if (!pressed) {
imageView.startAnimation(zoomIn);
pressed = !pressed;
} else {
imageView.startAnimation(zoomOut);
pressed = !pressed;
}
}
});
layout.addView(imageView);
// removing items from list
list.remove(0);
c++;
tempSize--;
}
containerLayout.addView(layout);
}
I have 3 row in table, where every row has 3 checkbox. I want to check appropriate CheckBox according to its id.
I have to check following ids CheckBox.
tempArray =[1-2-3,3-2,null];
i am already splitting these data and putting in string array(setopts).more see my code.
Null for no check any CheckBox with this row.
I am doing this code in my project.
Vector<CheckBox> chkBoxList = new Vector<CheckBox>();
Vector<TextView> txtViewList = new Vector<TextView>();
// mat_elemItemSetChk.get(0).size() OF VALUE IS 3
for (int n = 0; n < mat_elemItemSetChk.get(0).size(); n++) {
LinearLayout llayout = new LinearLayout(getContext());
ll.setOrientation(android.widget.LinearLayout.VERTICAL);
cb = new CheckBox(getContext());
tv = new TextView(getContext());
for (int r = 0; r < tempArray.size() ; r++) {
isContains=tempArray.get(r).contains(individualValueSeparator);
if(isContains){
setOpts = tempArray.get(r).split("\\-");
for (int k = 0; k < setOpts.length; k++)
{
ItemValue iv = (ItemValue) mat_elemItemSetChk.get(0).get(n);
if (((int) iv.getId()) == Integer.parseInt(setOpts[k]))
{
mat_elemItemSetChk.get(n).get(Integer.parseInt(setOpts[k])-1);
cb.setChecked(true);
}
}
}else{
if(tempArray.get(r).toString().equalsIgnoreCase("null")||tempArray.get(r).toString()!=null){
String temp;
String px[]= null;
temp = tempArray.get(r).toString();
ItemValue iv = (ItemValue) mat_elemItemSetChk.get(0).get(n);
if (((int) IV.getId()) == Integer.parseInt(temp))
{
mat_elemItemSetChk.get(0).get(Integer.parseInt(temp) - 1);
cb.setChecked(true);
}
}else{
cb.setChecked(false);
}
}
}
tv.setText(mat_elemItemSetChk.get(0).get(n) .toString());
llayout.addView(cb);
llayout.addView(tv);
chkBoxList.add(cb);
txtViewList.add(tv);
ll.addView(llayout);
// this.addView(tableLayout);
}
Thank you in advance.
make an array selchkboxlist and store the selected checkbox id in it and check condition like selchkboxlist.isEmpty() if true then then show error msg other wise go ahed...
selchkboxlist=new ArrayList<String>();
cbs = new CheckBox[8];
// generate dynamic item check box code
for(int k = 0; k<8; k++)
{
cbs[k] = new CheckBox(getApplicationContext());
#SuppressWarnings("deprecation")
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
rl.addView(cbs[k], params);
int j =k+1;
cbs[k].setText("ITEM" + j);
cbs[k].setTextColor(Color.parseColor("#000000"));
cbs[k].setId(k+1);
cbs[k].setPadding(70, 20, 10, 10);
// check box on click listener for add in to produduct array with quntity
cbs[k].setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
String chk = null;
if (((CheckBox) v).isChecked()) {
chk = Integer.toString(v.getId());
selchkboxlist.add(chk);
} else {
selchkboxlist.remove(chk);
}
}
});
}
// button on click listener code
b.setOnClickListener(new OnClickListener() {
#SuppressLint("SdCardPath")
public void onClick(View v) {
if (! selchkboxlist.isEmpty()) {
shoe erroe msg here
}else{
go ahed
}
}
});
Hello, my old code is working, but the problem is that when i am clicking tablerow it call another activty, but it not set that table row data but it setting last array data to that activity.
Means it set the last array value to next screen activity.
for ( j = 0; j < dataListfeture.size(); j++)
{
HashMap<String, String> hm = new HashMap<String, String>();
hm = dataListfeture.get(j);
final TableRow tblrow = new TableRow(MainScreen.this);
final View rowView = inflater.inflate(R.layout.featuredrow, null);
tblrow.setId(j);
tblrow.getId();
featuredName = (TextView) rowView.findViewById(R.id.xxName);
featuredDistance = (TextView) rowView.findViewById(R.id.xxDistance);
featuredVeneType = (TextView) rowView.findViewById(R.id.xxVeneType);
featuredPhone = (TextView) rowView.findViewById(R.id.xxPhone);
featuredAddress = (TextView) rowView.findViewById(R.id.xxAddress);
Drawable image = ImageOperations(MainScreen.this, hm.get("url"), "image.jpg");
featuredImage = (ImageView) rowView.findViewById(R.id.xxdImage);
featuredImage.setImageDrawable(image);
featuredName.setText("" + hm.get("name"));
featuredDistance.setText("" + hm.get("distance") + " mi");
featuredVeneType.setText("" + hm.get("venuetype"));
featuredPhone.setText("" + hm.get("phonenumber"));
featuredAddress.setText("" + hm.get("address"));
mapnamelist = hm.get("name");
mapvenuelist = hm.get("venuetype");
mapothervenuelist = hm.get("othervenuetype");
mapaddresslist= hm.get("address");
mapcitylist= hm.get("city");
mapstatelist= hm.get("state");
tblrow.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
final ProgressDialog progDailog = ProgressDialog.show(MainScreen.this, null, "Loading ....", true);
final Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
System.out.println("search");
Intent myIntent = new Intent(MainScreen.this, xxxxscreen.class);
startActivity(myIntent);
MainScreen.this.finish();
progDailog.dismiss();
}
};
new Thread()
{
public void run()
{
try
{
System.out.println();
handler.sendEmptyMessage(1);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}.start();
}
});
Create an int array of id say array_id[] and after setting id to table row add that id to array_id[] also like
tblrow.setId(j);
array_id[j] = j;
And in onClick method do this:
for(int i = 0;i< array_id.length;i++)
{
TableRow tbl_row = (TableRow) findViewById(i);
if(v.getId() == array_id[i])
{
/** Perform your Operations */
}
}