I am creating a application where I need to add imagebutton dynamatically,
under that imagebutton I want to set some text. I tried bellow posted code but I am getting exception at L.addView(btn);
Plz suggest something......
for (int i = 1; i <= SplashScreenActivity.num; i++)
{
LinearLayout L = new LinearLayout(this);
LayoutParams params_1 = new LayoutParams(241,137);
params_1.width=(int)(scaleX*241);
params_1.height=(int)(scaleY*137);
L.setLayoutParams(params_1);
ImageButton btn = new ImageButton(this);
File file= new File(Environment.getExternalStoragePublicDirectory("Android/data") + "/" + getApplicationContext().getPackageName()+"/CoverImages/skc_"+i+".jpg");
Bitmap bm = BitmapFactory.decodeFile(file.getPath());
btn.setImageBitmap(bm);
btn.setScaleType(ScaleType.FIT_XY);
btn.setBackgroundColor(80000000);
btn.setId(i);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(241, 137);
layoutParams.width=(int)(scaleX*241);
layoutParams.height=(int)(scaleY*137);
layoutParams.setMargins(24, 0, 24, 0);
ll.addView(btn, layoutParams);
TextView tv = new TextView(this);
tv.setGravity(Gravity.BOTTOM);
tv.setTextColor(Color.BLUE);
name = "purchased";
tv.setId(i);
tv.setText(name);
L.setOrientation(LinearLayout.HORIZONTAL);
btn.setMaxWidth(mButtonWidth);
btn.setMaxHeight(mButtonHeight);
L.addView(btn);
L.addView(tv);
ll .addView(L);
final int id_ = btn.getId();
btn = ((ImageButton) findViewById(id_));
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
utils.playTapSound();
File myDirectory = new File(Environment.getExternalStoragePublicDirectory("Android/data") + "/" + getApplicationContext().getPackageName() + "/ComicBook/comic"+MainPage.get_id+"/skc"+MainPage.get_id+".zip");
if(myDirectory.exists())
{
Intent intent = new Intent(MainPage.this,
FullScreenViewActivity.class);
startActivityForResult(intent, 0);
}
else
{
startService(new Intent(getApplicationContext(), BillingService.class));
Intent intent = new Intent(MainPage.this,InAppActivity.class);
startActivityForResult(intent, 0);
}
}
});
Related
I'm making a gallery in my application. I listed my images successfully and now adding its share buttons. Instead of directing user into another form, I'm trying to show share buttons above my image. For listing and sharing I need to create and add dynamic ImageButtons. But when I try to add share buttons, they're shown in wrong place. Here is my code:
LinearLayout ll = (LinearLayout) findViewById(R.id.llGallery);
for (int i = 0; i < jsonArray.length(); i++) {
final JSONObject jsonObject = jsonArray.getJSONObject(i);
final String Photo= jsonObject.getString("PhotoLink");
// PhotoDetails into another view
View.OnClickListener cPhotoDetails= new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GalleryDetailsActivity.this,
GalleryPhotoDetails.class);
intent.putExtra("Image", Photo);
startActivity(intent);
}
};
View.OnClickListener cShare= new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File myFile = new File(fotograf);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
Intent sharingIntent = new Intent("android.intent.action.SEND");
sharingIntent.setType(type);
sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
startActivity(Intent.createChooser(sharingIntent, "Share with"));
} catch (Exception e) {
// Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
};
RelativeLayout rel = new RelativeLayout(context);
rel.setGravity(Gravity.CENTER_VERTICAL);
ImageButton img = new ImageButton(context);
img.setClickable(true);
img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
Glide.with(context).load(Photo).into(img);
img.setOnClickListener(cPhotoDetails);
rel.addView(img);
ImageButton share = new ImageButton(context);
share.setClickable(true);
share.setScaleType(ImageView.ScaleType.FIT_XY);
Glide.with(context).load(R.drawable.btn_share).into(share);
share.setOnClickListener(cShare);
rel.addView(share);
ll.addView(rel);
}
RelativeLayout rel = new RelativeLayout(context);
rel.setGravity(Gravity.CENTER_VERTICAL);
ImageView img = new ImageView(context);
img.setClickable(true);
img.setScaleType(ImageView.ScaleType.FIT_XY);
Glide.with(context).load(Photo).into(img);
img.setOnClickListener(cPhotoDetails);
rel.addView(img);
ImageButton share = new ImageButton(context);
share.setClickable(true);
share.setScaleType(ImageView.ScaleType.FIT_XY);
Glide.with(context).load(R.drawable.btn_share).into(share);
share.setOnClickListener(cShare);
rel.addView(share);
ll.addView(rel);
It's been a few month since I am working heavely on this one app. Everything needs to be just perfect before the launch.
Now more and more functunallty is implemented and exactly that is the problem: The activities now start to be up to 1000 lines! Why is that, you may ask?
It is because of the layout that needs to be set programmatically.
In almost every activity in my app we have a scrollview that downloads content off a server and then puts it into a foreach loop. This renders it impossible to set most of the layout in the xmls. Just to scare you a little bit:
private void DrawLayoutFriends()
{
// Start with the header
frmHeaderFriends.SetBackgroundColor(Color.ParseColor("#38a0c2"));
frmHeaderFriends.LayoutParameters = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.MatchParent, intHeightOfDisplay / 7);
ImageButton btnHeader = new ImageButton(this);
btnHeader.SetBackgroundResource(Resource.Drawable.mainmenu_btn_news_friends);
btnHeader.Background.Mutate().SetColorFilter(new Color(Color.White), PorterDuff.Mode.SrcIn);
FrameLayout.LayoutParams paramsHeaderBtn = new FrameLayout.LayoutParams
(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
paramsHeaderBtn.Gravity = GravityFlags.Center;
TextView txtHeader = new TextView(this);
txtHeader.Text = "17 news!";
txtHeader.SetTypeface(font, TypefaceStyle.Normal);
txtHeader.SetTextColor(Color.ParseColor("#ffffff"));
FrameLayout.LayoutParams paramsForTextHeader = new FrameLayout.LayoutParams
(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
paramsForTextHeader.Gravity = GravityFlags.Bottom | GravityFlags.Right;
txtHeader.LayoutParameters = paramsForTextHeader;
btnHeader.LayoutParameters = paramsHeaderBtn;
frmHeaderFriends.AddView(btnHeader);
frmHeaderFriends.AddView(txtHeader);
// Now the loop
foreach (var friend in newfriends)
{
LinearLayout linlayForLoop = new LinearLayout(this);
LinearLayout.LayoutParams paramsForLinLayLoop = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WrapContent, intHeightOfDisplay / 2);
paramsForLinLayLoop.Gravity = GravityFlags.Center;
linlayForLoop.Orientation = Orientation.Vertical;
ImageButton btnAvatarOfFriend = new ImageButton(this);
btnAvatarOfFriend.SetBackgroundResource(Resource.Drawable.general_dummy_avatar_big);
LinearLayout.LayoutParams paramsForCenter = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
paramsForCenter.Gravity = GravityFlags.Center;
paramsForCenter.SetMargins(0, intHeightOfDisplay / 80, 0, 0);
btnAvatarOfFriend.LayoutParameters = paramsForCenter;
TextView txtNameOfFriend = new TextView(this);
txtNameOfFriend.Text = friend.fkUsername.ToUpper()+ " " +
Resources.GetString(Resource.String.AddedU);
txtNameOfFriend.TextSize = 18;
txtNameOfFriend.Gravity = GravityFlags.Center;
txtNameOfFriend.SetTypeface(font, TypefaceStyle.Normal);
txtNameOfFriend.SetTextColor(Color.ParseColor("#007762"));
LinearLayout.LayoutParams paramsForTextFriend = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
paramsForTextFriend.Gravity = GravityFlags.Center;
paramsForTextFriend.SetMargins(0, intHeightOfDisplay / 80, 0, 0);
txtNameOfFriend.LayoutParameters = paramsForTextFriend;
TextView txtSubLineFriends = new TextView(this);
txtSubLineFriends.Text = "traveler | lvl 99 | 999,999ap";
txtSubLineFriends.TextSize = 10;
txtSubLineFriends.SetTypeface(font, TypefaceStyle.Normal);
txtSubLineFriends.SetTextColor(Color.ParseColor("#000000"));
LinearLayout.LayoutParams paramsForTextSubLineFriend = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
paramsForTextSubLineFriend.Gravity = GravityFlags.Center;
txtSubLineFriends.LayoutParameters = paramsForTextSubLineFriend;
linlayForLoop.AddView(btnAvatarOfFriend);
linlayForLoop.AddView(txtNameOfFriend);
linlayForLoop.AddView(txtSubLineFriends);
btnAvatarOfFriend.Click += delegate
{
Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this);
alert.SetMessage("Hey there! I added you as my friend to follow your profile! Would you like to add me back? :-)");
alert.SetPositiveButton("Befriend Me!", (senderAlert, args) =>
{
Toast.MakeText(this, "Not yet possible", ToastLength.Short).Show();
});
alert.SetNegativeButton("Visit My Profile!", (senderAlert, args) =>
{
Toast.MakeText(this, "Not yet possible", ToastLength.Short).Show();
});
alert.SetNeutralButton("Dismiss Me!", (senderAlert, args) =>
{
TranslateAnimation animation = new TranslateAnimation(0, -2000, 0, 0);
animation.FillAfter = true;
animation.SetInterpolator(this, Android.Resource.Animation.AccelerateDecelerateInterpolator);
animation.Duration = intDurationOfAnimation;
btnAvatarOfFriend.StartAnimation(animation);
txtNameOfFriend.StartAnimation(animation);
txtSubLineFriends.StartAnimation(animation);
animation.AnimationEnd += delegate
{
linlayForLoop.RemoveAllViews();
};
});
Dialog dialog = alert.Create();
dialog.Show();
};
linlayForAddedFriends.AddView(linlayForLoop);
}
btnDismissAllLeft.Click += delegate
{
// TranslateAnimation animation = new TranslateAnimation(0, -2000, 0, 0);
// animation.FillAfter = true;
// animation.SetInterpolator(this, Android.Resource.Animation.AccelerateDecelerateInterpolator);
// animation.Duration = intDurationOfAnimation;
// btnAvatarOfFriend.StartAnimation(animation);
// txtNameOfFriend.StartAnimation(animation);
// txtSubLineFriends.StartAnimation(animation);
//
// animation.AnimationEnd += delegate
// {
// linlayForLoop.RemoveAllViews();
// };
};
//Put into side drawer
}
private void DrawLayoutBolNews()
{
// Start with the header
frmHeaderNews.SetBackgroundColor(Color.ParseColor("#38a0c2"));
frmHeaderNews.LayoutParameters = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.MatchParent, intHeightOfDisplay / 7);
ImageButton btnHeader = new ImageButton(this);
btnHeader.SetBackgroundResource(Resource.Drawable.mainmenu_btn_news_bol);
btnHeader.Background.Mutate().SetColorFilter(new Color(Color.White), PorterDuff.Mode.SrcIn);
FrameLayout.LayoutParams paramsHeaderBtn = new FrameLayout.LayoutParams
(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
paramsHeaderBtn.Gravity = GravityFlags.Center;
TextView txtHeader = new TextView(this);
txtHeader.Text = "17 news!";
txtHeader.SetTypeface(font, TypefaceStyle.Normal);
txtHeader.SetTextColor(Color.ParseColor("#ffffff"));
FrameLayout.LayoutParams paramsForTextHeader = new FrameLayout.LayoutParams
(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
paramsForTextHeader.Gravity = GravityFlags.Bottom | GravityFlags.Left;
txtHeader.LayoutParameters = paramsForTextHeader;
btnHeader.LayoutParameters = paramsHeaderBtn;
frmHeaderNews.AddView(btnHeader);
frmHeaderNews.AddView(txtHeader);
// Now the loop
LinearLayout linlayForLoop = new LinearLayout(this);
LinearLayout.LayoutParams paramsForLinLayLoop = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WrapContent, intHeightOfDisplay / 2);
paramsForLinLayLoop.Gravity = GravityFlags.Center;
linlayForLoop.Orientation = Orientation.Vertical;
ImageButton btnNews = new ImageButton(this);
btnNews.SetBackgroundResource(Resource.Drawable.general_imgv_news);
LinearLayout.LayoutParams paramsForCenter = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
paramsForCenter.Gravity = GravityFlags.Center;
paramsForCenter.SetMargins(0, intHeightOfDisplay / 80, 0, 0);
btnNews.LayoutParameters = paramsForCenter;
TextView txtInfo = new TextView(this);
txtInfo.Text = "123 new challenges unlocked!";
txtInfo.TextSize = 15;
txtInfo.SetTypeface(font, TypefaceStyle.Normal);
txtInfo.SetTextColor(Color.ParseColor("#007762"));
txtInfo.Gravity = GravityFlags.Center;
LinearLayout.LayoutParams paramsForTextFriend = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
paramsForTextFriend.Gravity = GravityFlags.Center;
paramsForTextFriend.SetMargins(0, intHeightOfDisplay / 80, 0, 0);
txtInfo.LayoutParameters = paramsForTextFriend;
linlayForLoop.AddView(btnNews);
linlayForLoop.AddView(txtInfo);
linlayForLoop.Click += delegate
{
Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this);
alert.SetPositiveButton("Dismiss!", (senderAlert, args) =>
{
TranslateAnimation animation = new TranslateAnimation(0, 2000, 0, 0);
animation.FillAfter = true;
animation.SetInterpolator(this, Android.Resource.Animation.AccelerateDecelerateInterpolator);
animation.Duration = intDurationOfAnimation;
txtInfo.StartAnimation(animation);
btnNews.StartAnimation(animation);
animation.AnimationEnd += delegate
{
linlayForLoop.RemoveAllViews();
};
});
alert.SetNeutralButton("Show!", (senderAlert, args) =>
{
Toast.MakeText(this, "Not yet possible", ToastLength.Short).Show();
});
Dialog dialog = alert.Create();
dialog.Show();
};
btnDismissAllRight.Click += delegate
{
TranslateAnimation animation = new TranslateAnimation(0, 2000, 0, 0);
animation.FillAfter = true;
animation.SetInterpolator(this, Android.Resource.Animation.AccelerateDecelerateInterpolator);
animation.Duration = intDurationOfAnimation;
txtInfo.StartAnimation(animation);
btnNews.StartAnimation(animation);
animation.AnimationEnd += delegate
{
linlayForLoop.RemoveAllViews();
};
};
//Put into side drawer
linlayForBolNews.AddView(linlayForLoop);
}
This is JUST the layout from two methods in one class. Not even everything.
This is veryinconvinient. Not only is the class extemely long, it is also very confusing to read and therefore fix in case something breaks.
Now my question:
What is the best way to handle programmatic layout inside my many classes / activities?
Have one class ONLY with layout functions and then send data back and forth when needed? This would get the layout out off the activities, yet it still remains impossible to read. Also, that one class then would easily reach 10k lines which is just rediculous...
I hope you guys can hint me towards the right way, before I start moving all layout files and then realize it was wrong.
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
i have created list linearlayout with my code
String[] name = {"Chicken", "Beef", "Milk" ,"Juice"};
final Integer[] price = {10, 50, 5, 3};
final Integer[] qty = {1, 2, 5, 5};
listOrder.removeAllViews();
LinearLayout.LayoutParams image = new LinearLayout.LayoutParams(Utility.getDip(175, CartActivity.this), Utility.getDip(70, CartActivity.this));
LinearLayout.LayoutParams text = new LinearLayout.LayoutParams(Utility.getDip(140, CartActivity.this), Utility.getDip(80, CartActivity.this));
LinearLayout.LayoutParams textQty = new LinearLayout.LayoutParams(Utility.getDip(100, CartActivity.this), Utility.getDip(80, CartActivity.this));
LinearLayout.LayoutParams textPrice = new LinearLayout.LayoutParams(Utility.getDip(125, CartActivity.this), Utility.getDip(80, CartActivity.this));
LinearLayout.LayoutParams textTotal = new LinearLayout.LayoutParams(Utility.getDip(130, CartActivity.this), Utility.getDip(80, CartActivity.this));
LinearLayout.LayoutParams editImage = new LinearLayout.LayoutParams(Utility.getDip(40, CartActivity.this), Utility.getDip(40, CartActivity.this));
for(int i = 0; i < 4; i++){
list = new LinearLayout(ctx);
list.setOrientation(LinearLayout.HORIZONTAL);
//if((i % 2) == 0) list.setBackgroundColor(R.color.bg_grey);
listImage = new ImageView(ctx);
//listImage.setImageDrawable(getResources().getDrawable(R.drawable.sample_logo_publisher));
listImage.setBackgroundColor(getResources().getColor(R.color.bg_grey));
listImage.setAdjustViewBounds(Boolean.TRUE);
listImage.setScaleType(ScaleType.FIT_XY);
image.gravity = Gravity.CENTER;
image.setMargins(Utility.getDip(10, CartActivity.this), 0, Utility.getDip(10, CartActivity.this), 0);
list.addView(listImage, image);
listText = new TextView(ctx);
listText.setText(name[i]);
listText.setGravity(Gravity.CENTER);
text.gravity = Gravity.CENTER;
text.setMargins(Utility.getDip(10, CartActivity.this), 0, 0, 0);
list.addView(listText, text);
listQty = new TextView(ctx);
listQty.setText(qty[i].toString());
listQty.setGravity(Gravity.CENTER);
textQty.gravity = Gravity.CENTER;
textQty.setMargins(Utility.getDip(5, CartActivity.this), 0, Utility.getDip(5, CartActivity.this), 0);
list.addView(listQty, textQty);
listPrice = new TextView(ctx);
listPrice.setText(price[i].toString());
listPrice.setGravity(Gravity.CENTER_VERTICAL);
textPrice.gravity = Gravity.CENTER;
list.addView(listPrice, textPrice);
Integer total = qty[i]*price[i];
listTotal = new TextView(ctx);
listTotal.setText(total.toString());
listTotal.setGravity(Gravity.CENTER_VERTICAL);
textTotal.gravity = Gravity.CENTER;
textTotal.setMargins(Utility.getDip(5, CartActivity.this), 0, Utility.getDip(2, CartActivity.this), 0);
list.addView(listTotal, textTotal);
plus = new ImageView(ctx);
plus.setImageDrawable(getResources().getDrawable(R.drawable.plus));
plus.setAdjustViewBounds(Boolean.TRUE);
plus.setScaleType(ScaleType.FIT_XY);
editImage.gravity = Gravity.CENTER;
list.addView(plus, editImage);
final int pos = i;
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
qty[pos] = qty[pos] + 1;
listQty.setText(qty[pos].toString());
listTotal.setText(""+ (qty[pos]*price[pos]));
}
});
minus = new ImageView(ctx);
minus.setImageDrawable(getResources().getDrawable(R.drawable.min));
minus.setAdjustViewBounds(Boolean.TRUE);
minus.setScaleType(ScaleType.FIT_XY);
editImage.gravity = Gravity.CENTER;
list.addView(minus, editImage);
remove = new ImageView(ctx);
remove.setImageDrawable(getResources().getDrawable(R.drawable.trash));
remove.setAdjustViewBounds(Boolean.TRUE);
remove.setScaleType(ScaleType.FIT_XY);
editImage.gravity = Gravity.CENTER;
list.addView(remove, editImage);
listOrder.addView(list);
}
I want to add quantity when onclick on plus image. But when i clicked plus image in the list, textQty changed in end of the list, not in the same list that I have clicked the image.
how to fix my code?
You need to link the TextViews and button together. They don't know they are in the same iteration of the for loop.
You could put each set of buttons and textviews into an array when you go through your loop.
Then in your onClickListener you would for do something like:
for(int i = 0; i < buttonArray.length; i++){
if(v == buttonArray[i]){
// make whatever changes to TextViews at index i
}
}
I have resolved my problem. Here is my code ...
I set id in listQty and listTotal
listQty = new TextView(ctx);
listQty.setId(99000+i);
listQty.setText(qty[i].toString());
listQty.setGravity(Gravity.CENTER);
textQty.gravity = Gravity.CENTER;
textQty.setMargins(Utility.getDip(5, CartActivity.this), 0, Utility.getDip(5, CartActivity.this), 0);
list.addView(listQty, textQty);
listTotal = new TextView(ctx);
listTotal.setId(98000+i);
listTotal.setText(total.toString());
listTotal.setGravity(Gravity.CENTER_VERTICAL);
textTotal.gravity = Gravity.CENTER;
textTotal.setMargins(Utility.getDip(5, CartActivity.this), 0, Utility.getDip(2, CartActivity.this), 0);
list.addView(listTotal, textTotal);
and in clicklistener set variable of listQty and listTotal
plus = new ImageView(ctx);
plus.setImageDrawable(getResources().getDrawable(R.drawable.plus));
plus.setAdjustViewBounds(Boolean.TRUE);
plus.setScaleType(ScaleType.FIT_XY);
editImage.gravity = Gravity.CENTER;
list.addView(plus, editImage);
final int pos = i;
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
listQty = (TextView)findViewById(99000+pos);
listTotal = (TextView)findViewById(98000+pos);
qty[pos] = qty[pos] + 1;
listQty.setText(qty[pos].toString());
listTotal.setText(""+ (qty[pos]*price[pos]));
}
});
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 ;-)