onclickListener in android - android

in my application i'm adding checkbox dyanmically.i want to perform operations on clicking on checkbox.
i tried a lot.below is the code.please help me.how can i get id's of clicked checkbox.in below code its not even entering in onclick function.
public class ImportFile extends Activity implements OnClickListener{
TableLayout tl;
Intent i;
ImageView im;
int idcount;
public OnClickListener checkBoxListener;
TextView nameoffile,sizeoffile,line;
CheckBox[] ch=new CheckBox[100];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylist);
tl=(TableLayout) findViewById(R.id.table);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator
+ "gallery" //folder name
);
if (!file.exists()) {
file.mkdirs();
}
/* i=new Intent();
i.putExtra("file","string");
setResult(RESULT_OK, i);
finish(); */
TableRow tr=new TableRow(this);
int id=1;
File f = new File("/sdcard/download");//or Environment.getExternalStorageDirectory().getPath()
File[] files = f.listFiles();
for(int i = 0; i < files.length; i++) {
File file1 = files[i];
//take the file name only
long size = file1.length()/1024;
String myfile = file1.getPath().substring(file1.getPath().lastIndexOf("/")+1,file1.getPath().length()).toLowerCase();
if(myfile.endsWith(".jpeg")||myfile.endsWith(".png")|| myfile.endsWith(".gif") || myfile.endsWith(".jpg"))
{
ch[id]=new CheckBox(getApplicationContext());
ch[id].setId(id);
ch[id].setText(" ");
System.out.println("id is........"+id);
Bitmap b=ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile((file1.getPath())), 40,40);
im=new ImageView(this);
im.setImageBitmap(b);
nameoffile=new TextView(this);
nameoffile.setText(" "+myfile);
nameoffile.setWidth(200);
sizeoffile=new TextView(this);
sizeoffile.setText(size+"KB");
sizeoffile.setWidth(100);
tr=new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
if((id%2)==0)
{
tr.setBackgroundResource(R.color.Thistle);
}
else{
tr.setBackgroundResource(R.color.Bisque);
}
tr.addView(ch[id++]);
idcount=id;
tr.addView(im);
tr.addView(nameoffile);
tr.addView(sizeoffile);
tr.setId(id);
tl.addView(tr,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
}
}
}
#Override
public void onClick(View v) {
int j;
// TODO Auto-generated method stub
for(j=1;j<idcount;j++){
if(ch[j].isChecked())
{
System.out.println("PPPPPPPPPPPPPPPPPP"+j);
}
}
}
}

You have to change the onCLick listener to onCheckChangedListener
public class ImportFile extends Activity implements OnCheckedChangeListener {
TableLayout tl;
Intent i;
ImageView im;
int idcount;
public OnClickListener checkBoxListener;
TextView nameoffile, sizeoffile, line;
CheckBox[] ch = new CheckBox[100];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylist);
tl = (TableLayout) findViewById(R.id.table);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator
+ "gallery" //folder name
);
if (!file.exists()) {
file.mkdirs();
}
/* i=new Intent();
i.putExtra("file","string");
setResult(RESULT_OK, i);
finish(); */
TableRow tr = new TableRow(this);
int id = 1;
File f = new File("/sdcard/download");//or Environment.getExternalStorageDirectory().getPath()
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
File file1 = files[i];
//take the file name only
long size = file1.length() / 1024;
String myfile = file1.getPath().substring(file1.getPath().lastIndexOf("/") + 1, file1.getPath().length()).toLowerCase();
if (myfile.endsWith(".jpeg") || myfile.endsWith(".png") || myfile.endsWith(".gif") || myfile.endsWith(".jpg")) {
ch[id] = new CheckBox(this);
ch[id].setId(id);
ch[id].setText(" ");
ch[id].setOnCheckedChangeListener(this);
System.out.println("id is........" + id);
Bitmap b = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile((file1.getPath())), 40, 40);
im = new ImageView(this);
im.setImageBitmap(b);
nameoffile = new TextView(this);
nameoffile.setText(" " + myfile);
nameoffile.setWidth(200);
sizeoffile = new TextView(this);
sizeoffile.setText(size + "KB");
sizeoffile.setWidth(100);
tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
if ((id % 2) == 0) {
tr.setBackgroundResource(R.color.Thistle);
}
else {
tr.setBackgroundResource(R.color.Bisque);
}
tr.addView(ch[id++]);
idcount = id;
tr.addView(im);
tr.addView(nameoffile);
tr.addView(sizeoffile);
tr.setId(id);
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
int kk = ch[1].getId();
System.out.println("PPPPPPPPPPPPPPPPPP" + kk);
}
}

change
ch[id]=new CheckBox(this);
to
ch[id] = new CheckBox(getApplicationContext());
It will solve your problem

Related

How do I sort the buttons generated from the following code alphabetically base on string values

<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);
...

java.lang.NumberFormatException: unable to parse '' as integer

i want to set the calculation result in TextView named total[] from the value of EditText named point[] .but i am able to parse the value and put it in the TextView . it give me an error in logcat
06-27 02:27:01.467: E/AndroidRuntime(275): Caused by: java.lang.NumberFormatException: unable to parse '' as integer
this is an error in logcat. i want to add integer values to the textview continuously from the edittext on the same layout
public class player_name extends Activity {
LinearLayout player_name;
TableLayout ply_name;
Bundle b,b1;
List<TextView> allEds = new ArrayList<TextView>();
List<Button> allplus = new ArrayList<Button>();
List<Button> allminus = new ArrayList<Button>();
List<EditText> alledit = new ArrayList<EditText>();
List<TextView> alltotal = new ArrayList<TextView>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_name);
b1 = getIntent().getExtras();
String[] result = b1.getStringArray("playerName");
player_name = (LinearLayout) findViewById(R.id.player_name);
ply_name = new TableLayout(this);
player_name.addView(ply_name);
TableLayout.LayoutParams tableRowParams=new TableLayout.LayoutParams
(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.MATCH_PARENT,1.0f);
TextView[] ed1 = new TextView[result.length+1];
Button[] plus = new Button[result.length+1];
Button[] minus = new Button[result.length+1];
EditText[] point = new EditText[result.length+1];
TextView[] total = new TextView[result.length+1];
TableRow[] TR= new TableRow[result.length+1];
int[] totalscore = null;
String[] temp = null;
Button btnResult = new Button(player_name.this);
btnResult.setText(" click here to get RESULT");
for(int i=0;i<=(result.length-1);i++) {
ed1[i] = new TextView(player_name.this);
plus[i] = new Button(player_name.this);
minus[i] = new Button(player_name.this);
point[i] = new EditText(player_name.this);
total[i] = new TextView(player_name.this);
TR[i] = new TableRow(player_name.this);
allEds.add(ed1[i]);
alltotal.add(total[i]);
alledit.add(point[i]);
allplus.add(plus[i]);
allminus.add(minus[i]);
TR[i].addView(ed1[i]);
TR[i].addView(point[i]);
TR[i].addView(plus[i]);
TR[i].addView(minus[i]);
TR[i].addView(total[i]);
ply_name.addView(TR[i]);
TR[i].setLayoutParams(tableRowParams);
totalscore[i] =Integer.parseInt(point[i].getText().toString());
temp[i] = "" + totalscore[i];
ed1[i].setId(i);
ed1[i].setHeight(50);
ed1[i].setWidth(70);
ed1[i].setText(result[i]);
ed1[i].setTextColor(Color.CYAN);
total[i].setId(i);
total[i].setHeight(50);
total[i].setWidth(70);
total[i].setText(""+0);
total[i].setTextColor(Color.CYAN);
point[i].setId(i);
point[i].setHeight(50);
point[i].setWidth(120);
point[i].setHint(result[i]+"\'s");
point[i].setInputType(InputType.TYPE_CLASS_NUMBER);
point[i].setTextColor(Color.BLACK);
plus[i].setId(i);
plus[i].setHeight(50);
plus[i].setWidth(50);
plus[i].setText("+");
plus[i].setTextColor(Color.BLACK);
minus[i].setId(i);
minus[i].setHeight(50);
minus[i].setWidth(50);
minus[i].setText("-");
minus[i].setTextColor(Color.BLACK);
plus[i].setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
minus[i].setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
}
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
player_name.addView(btnResult, lp);
btnResult.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent1 = new Intent(player_name.this,result.class);
startActivity(intent1);
}
});
}
}
You need to check whether the string you are parsing is an integer. Try this code:
if (IsInteger(point[i].getText().toString()))
totalscore[i] =Integer.parseInt(point[i].getText().toString());
and add this function:
public static boolean IsInteger(String s)
{
if (s == null || s.length() == 0) return false;
for(int i = 0; i < s.length(); i++)
{
if (Character.digit(s.charAt(i), 10) < 0)
return false;
}
return true;
}
I hope this helps

read data content in TableRow

I have a TableRow that is loaded dynamically. It contains multiple EditTexts and CheckBoxes. How do I get the user input from these EditTexts and CheckBoxes?
This my Code
public void cargarProductos(SQLiteDatabase db){
TableLayout tabla = (TableLayout) findViewById(R.id.Detalle);
Cursor cProd = db.rawQuery("SELECT * FROM vstEncProductos WHERE IdCliente="+idCliente+" AND Idcategoria="+IdCategoria, null);
int ValorChk = 0;
if (cProd.moveToFirst()) {
do {
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
row.setId(cProd.getInt(0));
ImageButton btnBarCode = new ImageButton(this);
btnBarCode.setBackgroundResource(R.drawable.barcodereader48);
btnBarCode.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");
startActivityForResult(intent, 0);
};
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
showDialog(R.string.result_succeeded, "Format: " + format + "\nContents: " + contents);
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
});
row.addView(btnBarCode, new TableRow.LayoutParams(0));
TextView txtProducto = new TextView(this);
txtProducto.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
txtProducto.setText(cProd.getString(1));
txtProducto.setWidth(230);
row.addView(txtProducto, new TableRow.LayoutParams(1));
EditText txtPrecio = new EditText(this);
txtPrecio.setWidth(130);
txtPrecio.setInputType(InputType.TYPE_CLASS_NUMBER);
row.addView(txtPrecio, new TableRow.LayoutParams(2));
TextView txtPrecioAnt = new TextView(this);
txtPrecioAnt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
txtPrecioAnt.setText(cProd.getString(7));
txtPrecioAnt.setWidth(115);
txtPrecioAnt.setGravity(Gravity.RIGHT);
row.addView(txtPrecioAnt, new TableRow.LayoutParams(3));
CheckBox chkPresencia = new CheckBox(this);
ValorChk=cProd.getInt(4);
chkPresencia.setChecked(ValorChk==-1);
chkPresencia.setWidth(50);
row.addView(chkPresencia, new TableRow.LayoutParams(4));
CheckBox chkPrecioPromo = new CheckBox(this);
ValorChk=cProd.getInt(4);
chkPrecioPromo.setChecked(ValorChk==-1);
chkPrecioPromo.setWidth(50);
row.addView(chkPrecioPromo, new TableRow.LayoutParams(4));
CheckBox chkAlerta = new CheckBox(this);
ValorChk=cProd.getInt(4);
chkAlerta.setChecked(ValorChk==-1);
chkAlerta.setWidth(50);
row.addView(chkAlerta, new TableRow.LayoutParams(4));
tabla.addView(row, new TableLayout.LayoutParams());
} while (cProd.moveToNext());
}
cProd.close();
I'm assuming you're using some sort of adapter class to load the data into your table. When you create a view, simply assign an OnClickListener to the checkboxes and a TextWatcher to the EditTexts. Use the callbacks from these classes to do what ever it is you want with the users input. Am I understanding your question correctly?
when you are creating new tablerows you can save each file in a multi vector of, for example, strings. Then you only must get size of each vector inside theparent vector. My example with your cody modified:
Vector<Vector<String>> result = new Vector<Vector<String>>();
Vector<String> vecAux = new Vector<String>();
TextView txtProducto = new TextView(this);
txtProducto.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
txtProducto.setText(cProd.getString(1));
txtProducto.setWidth(230);
row.addView(txtProducto, new TableRow.LayoutParams(1));
vecAux.add(cProd.getString(1));
EditText txtPrecio = new EditText(this);
txtPrecio.setWidth(130);
txtPrecio.setInputType(InputType.TYPE_CLASS_NUMBER);
row.addView(txtPrecio, new TableRow.LayoutParams(2));
TextView txtPrecioAnt = new TextView(this);
txtPrecioAnt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
txtPrecioAnt.setText(cProd.getString(7));
txtPrecioAnt.setWidth(115);
txtPrecioAnt.setGravity(Gravity.RIGHT);
row.addView(txtPrecioAnt, new TableRow.LayoutParams(3));
vecAux.add(cProd.getString(7));
CheckBox chkPresencia = new CheckBox(this);
ValorChk=cProd.getInt(4);
chkPresencia.setChecked(ValorChk==-1);
chkPresencia.setWidth(50);
row.addView(chkPresencia, new TableRow.LayoutParams(4));
CheckBox chkPrecioPromo = new CheckBox(this);
ValorChk=cProd.getInt(4);
chkPrecioPromo.setChecked(ValorChk==-1);
chkPrecioPromo.setWidth(50);
row.addView(chkPrecioPromo, new TableRow.LayoutParams(4));
CheckBox chkAlerta = new CheckBox(this);
ValorChk=cProd.getInt(4);
chkAlerta.setChecked(ValorChk==-1);
chkAlerta.setWidth(50);
row.addView(chkAlerta, new TableRow.LayoutParams(4));
tabla.addView(row, new TableLayout.LayoutParams());
result.add(vecAux);
And get results looking for all position of the vector:
String texto = "";
for (int i = 0; i < result.size(); i++) {
for (int j = 0; j < result.elementAt(i).size(); j++) {
texto += result.elementAt(i).elementAt(j) + "\t";
}
}
For get if checkbox is checked or not you can get it by ID (findViewById).
I hope help you, bye bye ;-)

Getting id of imageview

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();
}

Display is ADDING UP with TABLELAYOUT

I am creating a calendar using tablelayout as my display to the screen. However when I need to update the display with either new month or year being selected by the user, it only adds up to the previouse stored data into the table.
HERE is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
table = new TableLayout(this);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
table.setLayoutParams(lp);
table.setStretchAllColumns(true);
rowLp2 = new TableLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT,
1.0f);
cellLp2 = new TableRow.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT,
1.0f);
// cellLp3 = new TableRow.LayoutParams(arg0, arg1)
setYYMMDD(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_WEEK));
leadGap = new GregorianCalendar(yy, mm, 1).get(Calendar.DAY_OF_WEEK) - 1;
//calling methods
header();
weeks();
//setLeadGap(2011, 2);
days(dom[mm]);
setContentView(table);
}
private void days(int noDays)
{
TableRow row = new TableRow(this);
int d=1;
nRow = (leadGap > 3) ? nRow+1 : nRow;
//textMonth.setText(Integer.toString(nRow));
for (int r = 0; r <nRow ; ++r)
{
row = new TableRow(this);
if (r==0)
{ int l = 0;
for (int f = 1; f<7; ++f)
{
if( l <leadGap)
{
TextView v = new TextView(this);
v.setText("");
row.addView(v, cellLp2);
l++;
}
if (l == leadGap)
{
Button v = new Button(this);
v.setText(Integer.toString(d));
row.addView(v, cellLp2);
d++;
}
row.setBackgroundColor(Color.rgb(55, 254, 55));
}
}
else
{
for (int f = 0; f < 7; ++f)
{
if (d <= noDays)
{
//Button btn = new Button(this);
//btn.setText(Integer.toString(d));
//row.addView(btn, cellLp2);
Button v = new Button(this);
v.setText(Integer.toString(d));
row.addView(v, cellLp2);
row.setBackgroundColor(Color.rgb(55, 254, 55));
d++;
}
else
{
TextView btn = new TextView(this);
btn.setText("");
row.addView(btn, cellLp2);
}
}
}
table.addView(row, rowLp2);
}
}
private void header(){
headertbl= new TableLayout(this);
btnMonthPos = new Button(this);
btnMonthPos.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (iMonth > 10)
{
iMonth = 0;
}
else
{
iMonth += 1;
}
setLeadGap(iYear, iMonth);
days(dom[iMonth]);
textMonth.setText(months[iMonth]);
//recompute();
}
});
textMonth = new TextView(this);
btnMonthNeg = new Button(this);
btnMonthNeg.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (iMonth < 1)
{
iMonth = 11;
}
else
{
iMonth -= 1;
}
textMonth.setText(months[iMonth]);
}
});
btnYearPos = new Button(this);
btnYearPos.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
iYear += 1;
textYear.setText(Integer.toString(iYear));
leadGap = new GregorianCalendar(yy, mm, 1).get(Calendar.DAY_OF_WEEK) - 1;
//sunBtn.setText(Integer.toString(leadGap));
}
});
textYear = new TextView(this);
btnYearNeg = new Button(this);
btnYearNeg.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
iYear -= 1;
textYear.setText(Integer.toString(iYear));
}
});
//setting values during loading
btnMonthPos.setText("++");
textMonth.setText(months[mm]);
btnMonthNeg.setText("--");
btnYearPos.setText("++");
textYear.setText(Integer.toString(calendar.get(Calendar.YEAR)));
btnYearNeg.setText("--");
TableRow headerRow = new TableRow(this);
headerRow.addView(btnMonthPos, cellLp2);
headerRow.addView(textMonth, cellLp2);
headerRow.addView(btnMonthNeg, cellLp2);
headerRow.addView(btnYearPos, cellLp2);
headerRow.addView(textYear, cellLp2);
headerRow.addView(btnYearNeg, cellLp2);
headertbl.addView(headerRow, rowLp2);
table.addView(headertbl);
}
private void weeks()
{
String[] weekName = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
tblWeek = new TableLayout(this);
TableRow rowWeek = new TableRow(this);
for (int i = 0; i<1; i++)
{
rowWeek = new TableRow(this);
for (int j=0; j<weekName.length;j++)
{
TextView day = new TextView(this);
day.setText(" "+weekName[j]);
day.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
rowWeek.addView(day, cellLp2);
}
rowWeek.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
tblWeek.addView(rowWeek, rowLp2);
}
table.addView(tblWeek);
}
}
Consider deleting the old tablerows before adding new rows in weeks() day() and other function to the table(Tablelayout)

Categories

Resources