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.
Related
In this code i am able to create gridlayout. but the first item is in default view and the rest is like what i want. I try debug and I couldn't see what is wrong. Would you help me to solve this.
question="this is a sentence";
String sLetter;
String question = question.replace(" ", "");
//char[] charAr = question.toCharArray();
final ArrayList<String> letters = new ArrayList<>();
for (int k = 0; k < question.length(); k++) {
sLetter = Character.toString(question.charAt(k));
letters.add(sLetter);
}
Collections.sort(letters);
int i;
for (i = 0; i < letters.size();) {
int count = recursiveMethod(letters,i,1);
if (count>0) {
//region text add
View main_view = new View(context);
main_view.setLayoutParams(new LinearLayout.LayoutParams(100, ViewGroup.LayoutParams.WRAP_CONTENT));
gridLayout.setColumnCount(7);
if (question.length()<=7){
gridLayout.setRowCount(1);
}else if (question.length()<12){
gridLayout.setRowCount(2);
}else {
gridLayout.setRowCount(3);
}
GridLayout.Spec colSpan = GridLayout.spec(GridLayout.UNDEFINED,1);
GridLayout.Spec rowSpan = GridLayout.spec(GridLayout.UNDEFINED, 1);
GridLayout.LayoutParams gridParam = new GridLayout.LayoutParams(
rowSpan, colSpan);
gridParam.setGravity(Gravity.FILL_HORIZONTAL);
gridParam.setMargins(5, 10, 5, 10);
final TextView tv = new TextView(context);
tv.setText(letters.get(i).toUpperCase());
tv.setId(i);
tv.setPadding(15, 15, 15, 15);
tv.setTextColor(getResources().getColor(R.color.colorPrimaryLight));
RelativeLayout.LayoutParams relTv = new RelativeLayout.LayoutParams(80, ViewGroup.LayoutParams.WRAP_CONTENT);
relTv.addRule( RelativeLayout.CENTER_HORIZONTAL);
relTv.addRule( RelativeLayout.CENTER_VERTICAL);
tv.setLinksClickable(true);
tv.setTextSize(0, 60);
//tv.setLayoutParams(relTv);
CardView cardView = new CardView(context);
cardView.setCardBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
cardView.setRadius(10);
cardView.setCardElevation(5);
RelativeLayout relativeLayout = new RelativeLayout(context);
relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
final TextView textCount = new TextView(context);
textCount.setText(Integer.toString(count));
RelativeLayout.LayoutParams relParam = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
relParam.addRule(RelativeLayout.ALIGN_BOTTOM, i);
relParam.addRule(RelativeLayout.RIGHT_OF, i);
textCount.setTypeface(Typeface.DEFAULT_BOLD);
textCount.setTextColor(getResources().getColor(R.color.colorPrimaryLight));
textCount.setTextSize(0, 30);
textCount.setPadding(0,5,5,0);
//textCount.setLayoutParams(relParam);
relativeLayout.addView(tv,relTv);
relativeLayout.addView(textCount,relParam);
cardView.addView(relativeLayout);
//llLetters.addView(tv, lp);
gridLayout.addView(cardView,gridParam);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, tv.getText()+ "" + textCount.getText(), Toast.LENGTH_SHORT).show();
}
});
//llLetters.addView(gridLayout);
//endregion
i = i + count;
}
else {
i++;
}
}
The first letter of image is at the top left. I want to show that at the bottom right side of the letter. Would you help me to solve problem? Thanks =)
The problem lies here:
relParam.addRule(RelativeLayout.ALIGN_BOTTOM, i);
relParam.addRule(RelativeLayout.RIGHT_OF, i);
If you pass a zero to addRule, it is interpreted as false. Therefore you say, that ALIGN_BOTTOM should be false in your first letter, when i is zero.
See the documentation:
parameter: subject, int: the ID of another view to use as an anchor, or a boolean value (represented as RelativeLayout.TRUE for true or 0 for false).
I have a LinearLayout object and want to dynamically change the background image with a dynamically adding image object (it changes its color dynamically).
here is the code :
if (categoryResponse != null && categoryResponse.result != null
&& categoryResponse.result.length > 0) {
int i = 0;
category = new TextView[categoryResponse.result.length];
for (Category cat : categoryResponse.result) {
category[i] = new TextView(getActivity());
LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
par.setMargins(0, 10, 0, 0);
category[i].setLayoutParams(par);
category[i].setGravity(Gravity.CENTER);
category[i].setText(cat.name);
category[i].setTag(cat.id);
category[i].setPadding(0, 10, 0, 10);
category[i].setTextSize(25);
category[i].setBackgroundResource(R.drawable.category);
category[i].setTypeface(Global.AppsFont);
category[i].setTextColor(getResources().getColor(
R.color.white));
main.addView(category[i]);
//System.out.println("header textview width = " +category[i].getWidth() + "");
category[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String id = (String) v.getTag();
for (Entry<String, LinearLayout> entry : channels
.entrySet()) {
if (entry.getKey().equals(id)) {
entry.getValue().setVisibility(
View.VISIBLE);
} else
entry.getValue().setVisibility(
View.GONE);
}
}
});
i++;
LinearLayout LLM = null;
LLM = new LinearLayout(getActivity());
channels.put(cat.id, LLM);
LLM.setOrientation(LinearLayout.VERTICAL);
LLM.setVisibility(View.GONE);
LinearLayout.LayoutParams LLParamsm = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
LLParamsm.setMargins(0, 0, 0, 0);
LLM.setPadding(0, 0, 0, 0);
LLM.setLayoutParams(LLParamsm);
LLM.setBackgroundResource(R.drawable.category_bg);
main.addView(LLM);
LinearLayout LL = null;
int j = 0;
ChannelResponse channelResponse = JsonUtils
.getChannel(cat.id);
channelResponseData.put(cat.id, channelResponse);
if (channelResponse != null
&& channelResponse.result != null
&& channelResponse.result.length > 0) {
for (Channel chan : channelResponse.result) {
if (j % 2 == 0) {
LL = new LinearLayout(getActivity());
LinearLayout.LayoutParams LLParams = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
LL.setOrientation(LinearLayout.HORIZONTAL);
LL.setWeightSum(1);
LL.setLayoutParams(LLParams);
LLM.addView(LL);
}
Button chn = new Button(getActivity());
LinearLayout.LayoutParams ladderFLParams = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 0.5f);
ladderFLParams.setMargins(10, 10, 10, 10);
chn.setBackgroundResource(R.drawable.gray_selector);
chn.setGravity(Gravity.CENTER);
chn.setLayoutParams(ladderFLParams);
chn.setText(chan.name);
chn.setTag(chan.id);
chn.setTextSize(25);
chn.setTextColor(getResources().getColor(
R.color.black));
chn.setTypeface(Global.AppsFont);
chn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
channelIdid = (String) v.getTag();
createDialogBox(v);
}
});
LL.addView(chn);
channel.add(chn);
j++;
}
if (j % 2 != 0) {
Button chn = new Button(getActivity());
LinearLayout.LayoutParams ladderFLParams = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT, 0.5f);
ladderFLParams.setMargins(10, 10, 10, 10);
chn.setBackgroundResource(R.drawable.gray_selector);
chn.setGravity(Gravity.CENTER_HORIZONTAL
| Gravity.CENTER_VERTICAL);
chn.setLayoutParams(ladderFLParams);
chn.setVisibility(View.INVISIBLE);
chn.setTextSize(25);
chn.setTextColor(getResources().getColor(
R.color.black));
chn.setTypeface(Global.AppsFont);
LL.addView(chn);
channel.add(chn);
}
}
}
}'
9-patch images automatically add the padding that is built into the 9-patch, as padding to the view. Thus when you call LLM.setPadding(0, 0, 0, 0) that is being overridden when you call LLM.setBackgroundResource.
Here is the doc about 9-patches: http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch
If you don't want padding, your best option would be to design your 9-patch without padding, in other words with both the drawable and stretchable areas going to the edge of the image.
I suppose you could also try calling setPadding after setBackgroundResource, but I'm not sure if that would work. Really you should just design your background with your desired padding in mind.
Does that make sense?
I have code to create view programmatically like this ,
splash.post(new Runnable() {
#Override
public void run() {
processFromDatabase();
}
});
splash is my parent view , and this is processFromDatabase Code
private void processFromDatabase() {
createLayoutBook("food_name", "80000", "food_des","", 2);
Bitmap bmp = merge();
saveToLocal2(bmp);
}
and this is my code for createLayoutBook ,
private void createLayoutBook(String food_name, String food_price,String food_des, String path, int tag) {
Log.e("create layout book", "Create layout book");
RelativeLayout root_2book = new RelativeLayout(c);
RelativeLayout.LayoutParams rlp_a = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, ((int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 120, c.getResources()
.getDisplayMetrics())));
rlp_a.setMargins(0, 10, 0, 0);
root_2book.setLayoutParams(rlp_a);
root_2book.setBackgroundColor(c.getResources().getColor(R.color.krem));
RelativeLayout layout_detail_2book = new RelativeLayout(c);
RelativeLayout.LayoutParams rdet = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
rdet.addRule(RelativeLayout.RIGHT_OF, layout_a_2book.getId());
rdet.setMargins(20, 3, 0, 0);
layout_detail_2book.setLayoutParams(rdet);
TextView tv_nama_2book = new TextView(c);// nama
tv_nama_2book.setId(id_book);
id_book = id_book + 1;
RelativeLayout.LayoutParams tv_nama = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tv_nama_2book.setLayoutParams(tv_nama);
tv_nama_2book.setTextSize(20);
tv_nama_2book.setTypeface(Typeface.DEFAULT_BOLD);
tv_nama_2book.setText(food_name);
Log.e("food name", food_name);
getSharedPreferences("myprefs", 0).edit().putString("food_name", food_name).commit();
TextView tv_des_2book = new TextView(c); // des
RelativeLayout.LayoutParams tv_des = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tv_des.addRule(RelativeLayout.BELOW, tv_nama_2book.getId());
tv_des.setMargins(0, 3, 5, 0);
tv_des_2book.setLayoutParams(tv_des);
tv_des_2book.setTextSize(12);
tv_des_2book.setTextColor(c.getResources().getColor(R.color.hitam));
tv_des_2book.setText(food_des);
Log.e("food des", food_des);
getSharedPreferences("myprefs", 0).edit().putString("food_des", food_des).commit();
layout_detail_2book.addView(tv_nama_2book);
layout_detail_2book.addView(tv_des_2book);
root_2book.addView(layout_detail_2book);
splash.addView(root_2book);
and this is code for change this layout to bitmap
public Bitmap merge() {
View v1 = splash;
v1.setDrawingCacheEnabled(true);
Bitmap merge = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
return merge;
}
But why , it return with black screen , like my layout that I created before not save or missing , any solution?? thanks
I believe what you want something like this:
public Bitmap merge() {
Bitmap bitmap = Bitmap.createBitmap(...);
Canvas canvas = new Canvas(bitmap);
splash.draw(canvas);
return bitmap;
}
I have created dynamic layout that picks out data from xml and then create layout based on that.
I want to retain what I have written in in edittext and hence get the filled value.
But I am not getting success.
public void generateFields()
{
ll.removeAllViewsInLayout();
for(;i<=GenericXMLParser.nooffields;)
{
for(int j=i;j<i+3 ;j++)
{
if((j+1)>GenericXMLParser.nooffields)
{
break;
}
if(isonphone.get(j).equalsIgnoreCase("false"))
{
Log.i("isonphone", isonphone.get(j));
TextView textview = new TextView(this);
textview.setText(field.get(j));
textview.setTextSize(30);
textview.setTextColor(Color.parseColor("#000000"));
ll.addView(textview);
if(typefield.get(j).equalsIgnoreCase("text"))
{
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(0, 5, 0, 15); // llp.setMargins(left, top, right, bottom);
EditText et = new EditText(this);
et.setHint(field.get(j));
et.setTextSize(30);
et.setLayoutParams(llp);
et.setTextColor(Color.parseColor("#000000"));
et.setBackgroundResource(R.drawable.genericedittext);
ll.addView(et);
savePreferences("field"+j,et.getText().toString().trim());
texts.add(et.getText().toString().trim());
Toast.makeText(getApplicationContext(), "field"+i+texts, 1).show();
}
else if(typefield.get(j).equalsIgnoreCase("boolean"))
{
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(0, 5, 0, 15); // llp.setMargins(left, top, right, bottom);
RadioGroup rg = new RadioGroup(this);
RadioButton rb1 = new RadioButton(this);
RadioButton rb2 = new RadioButton(this);
rg.setOrientation(RadioGroup.HORIZONTAL);
rg.setLayoutParams(llp);
rb1.setText("Yes");
rb2.setText("No");
rb1.setTextColor(Color.parseColor("#000000"));
rb2.setTextColor(Color.parseColor("#000000"));
rb1.setTextSize(30);
rb2.setTextSize(30);
rg.addView(rb1);
rg.addView(rb2);
ll.addView(rg);
}
else if(typefield.get(j).equalsIgnoreCase("numeric"))
{
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(0, 5, 0, 15); // llp.setMargins(left, top, right, bottom);
EditText et = new EditText(this);
et.setHint(field.get(j));
et.setTextSize(30);
et.setLayoutParams(llp);
et.setInputType(InputType.TYPE_CLASS_NUMBER);
et.setTextColor(Color.parseColor("#000000"));
et.setBackgroundResource(R.drawable.genericedittext);
ll.addView(et);
}
}
this.setContentView(rl);
}
break;
}
//Toast.makeText(getApplicationContext(), "i="+i, 1).show();
if(i>GenericXMLParser.nooffields)
{
//Take me to the summary page.
Intent gmsIntent = new Intent(getApplicationContext(),
//GateManagementActivity.class);
GateManagementActivity.class);
gmsIntent.putExtra("userId", userId);
gmsIntent.putExtra("clientId", clientId);
startActivity(gmsIntent);
}
i+=3;
}
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]));
}
});