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?
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).
Iam creating the survey app with firebase Realtimedatabase.I have stored questions in database and getting them in application by dynamically creating RadioButtons,Textview and Edittext.
Now I have to save the filled information from users back to firebase database.I searched and get to know to use setTags but couldnt really able to understand after setting tags how to seperate edittext and radio buttons and get them back separately while pushing them to firebase database.What I want is to get the data from each edittext and radiobutton selected and save them back uniquely in firebase database
Here is the code where Iam creating views dynamically and getting data in them
if (getIntent().hasExtra(Constants.ref_no)) {
surveyRefNo = getIntent().getStringExtra(Constants.ref_no);
}
if (getIntent().hasExtra(Constants.refChild)) {
surveyRefChild = getIntent().getStringExtra(Constants.refChild);
}
databaseReference = FirebaseDatabase.getInstance().getReference().child(Constants.content).child(Constants.survey).child(surveyRefNo).child(surveyRefChild);
System.out.println(databaseReference);
System.out.println(surveyRefNo);
linearLayout = findViewById(R.id.survey_question_linearlayout);
databaseReference.child(Constants.questions).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds);
if (ds.hasChildren() && ds.hasChild("title") && ds.hasChild("type") && ds.hasChild("options")) {
for (DataSnapshot option : ds.child("options").getChildren()) {
values.add(String.valueOf(option.getValue()));
System.out.println(values);
System.out.println(values.size());
}
String user = String.valueOf(ds.child("type").getValue());
title = (String) ds.child("title").getValue();
switch (Integer.parseInt(user)) {
case (1):
if (user != null) {
addRadioButtons();
values.clear();
}
break;
case (2):
if (user != null) {
questionView();
}
break;
default:
Toast.makeText(GetSurveys.this, "Sorry!!! Something went wrong", Toast.LENGTH_SHORT).show();
}
} else if (ds.hasChildren() && ds.hasChild("title") && ds.hasChild("type")) {
String user = String.valueOf(ds.child("type").getValue());
title = (String) ds.child("title").getValue();
switch (Integer.parseInt(user)) {
case (1):
if (user != null) {
addRadioButtons();
}
break;
case (2):
if (user != null) {
questionView();
}
break;
default:
Toast.makeText(GetSurveys.this, "Sorry!!! Something went wrong", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void addRadioButtons() {
CardView cardView = new CardView(this);
LinearLayout.LayoutParams cardParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
cardParams.setMargins(10, 10, 10, 10);
cardView.setLayoutParams(cardParams);
cardView.setCardBackgroundColor(Color.parseColor("#f8f8ff"));
LinearLayout cardLayout = new LinearLayout(this);
cardLayout.setOrientation(LinearLayout.VERTICAL);
cardView.addView(cardLayout);
linearLayout.addView(cardView);
TextView radioText = new TextView(this);
radioText.setText(title);
LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
textParams.setMargins(10, 10, 10, 10);
radioText.setLayoutParams(textParams);
cardLayout.addView(radioText);
RadioGroup radioGroup = new RadioGroup(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10, 10, 10, 10);
radioGroup.setLayoutParams(params);
radioGroup.setOrientation(LinearLayout.VERTICAL);
for (int index = 0; index < values.size(); index++) {
RadioButton radioButton = new RadioButton(this);
radioButton.setId(View.generateViewId());
radioButton.setText(values.get(index));
radioGroup.addView(radioButton);
}
cardLayout.addView(radioGroup);
}
public void questionView() {
CardView cardView = new CardView(this);
LinearLayout.LayoutParams cardParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
cardParams.setMargins(10, 10, 10, 10);
cardView.setLayoutParams(cardParams);
cardView.setCardBackgroundColor(Color.parseColor("#f8f8ff"));
LinearLayout cardLayout = new LinearLayout(this);
cardLayout.setOrientation(LinearLayout.VERTICAL);
cardView.addView(cardLayout);
linearLayout.addView(cardView);
TextView questionText = new TextView(this);
LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
textParams.setMargins(20, 10, 20, 10);
questionText.setPadding(15, 10, 10, 10);
questionText.setText(title);
questionText.setGravity(16);
questionText.setTextSize(17.0f);
questionText.setLayoutParams(textParams);
cardLayout.addView(questionText);
EditText answerText = new EditText(this);
LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
editParams.setMargins(20, 5, 20, 5);
answerText.setPadding(15, 10, 10, 10);
answerText.setHint("Your Answer");
answerText.setTextSize(17.0f);
answerText.setLayoutParams(editParams);
cardLayout.addView(answerText);
}
}
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.
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 want this table to extend as possible to fill the remaining (empty) area of the linear layout that contains it
I generate the table using the following method
public void drawTable(LinearLayout tableLayout,String tableTitle, String[][] data,String[] headerTitles, int type){
//clearing previous views
tableLayout.setVisibility(View.VISIBLE);
tableLayout.setGravity(Gravity.CENTER);
int chids = tableLayout.getChildCount();
if (chids > 0){
tableLayout.removeAllViews();
}
if((headerTitles!= null) && (headerTitles.length != data[0].length) ){
return;
}
TableLayout table = new TableLayout(context);
// table.setStretchAllColumns(true);
// table.setShrinkAllColumns(true);
//Rendering the table title
TextView tableTitleView = new TextView(context);
tableTitleView.setText(tableTitle);
tableTitleView.setTextColor(Color.WHITE);
tableTitleView.setGravity(Gravity.CENTER);
tableTitleView.setTextSize(18);
tableTitleView.setTextAppearance(context, R.style.boldText);
tableTitleView.setBackgroundColor(Color.parseColor("#008888"));
tableTitleView.setPadding(2, 2, 2, 10);
tableLayout.addView(tableTitleView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
ScrollView scroll1 = new ScrollView(context);
HorizontalScrollView scroll2 = new HorizontalScrollView(context);
int rows = data.length;
int columns = data[0].length;
if(headerTitles!=null){
//Rendering the header
TableRow headerRow = new TableRow(context);
for (int i = 0; i < columns; i++) {
TextView t = new TextView(context);
t.setTextSize(17);
t.setTextAppearance(context, R.style.boldText);
t.setPadding(5, 5, 5, 5);
t.setText(headerTitles[i]);
t.setGravity(Gravity.CENTER);
t.setTextColor(Color.WHITE);
t.setBackgroundResource(R.drawable.text_border_header_1);
headerRow.addView(t, LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
}
table.addView(headerRow, new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
//Rendering the Table Data
TableRow row;
for (int current = 0; current < rows ; current++) {
row = new TableRow(context);
TextView t;
for(int i =0 ; i < columns ; i++){
t = new TextView(context);
t.setTextSize(15);
t.setPadding(5,5,5,5);
t.setText(data[current][i]);
t.setGravity(Gravity.CENTER);
if (type == 1) {
if (current % 2 == 0) {
t.setBackgroundResource(R.drawable.text_border_odd);
} else {
t.setBackgroundResource(R.drawable.text_border_even);
}
}else if (type == 2) {
if (current % 2 == 0) {
t.setBackgroundResource(R.drawable.text_border_odd_2);
} else {
t.setBackgroundResource(R.drawable.text_border_even_2);
}
}else if (type == 3) {
if (current % 2 == 0) {
t.setBackgroundResource(R.drawable.text_border_odd_3);
} else {
t.setBackgroundResource(R.drawable.text_border_even_3);
}
}
t.setTextColor(Color.BLACK);
row.addView(t,TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
}
table.addView(row, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
scroll2.addView(table,LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
scroll1.addView(scroll2,LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
scroll1.setPadding(2, 20, 2, 20);
tableLayout.addView(scroll1,LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
}
I couldn't figure out exactly the problem with my code.
EDIT :
when I added the table directly to the linear layout instead of the scroll views the table fits with the linear layout width. It seems that my problem is with the scroll view
I found the answer Here (thanks to Felix)
Just a single line of code to be added to the scroll views
scrollView.setFillViewPort(true);
try this on your TableLayout object.
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.width = LayoutParams.FILL_PARENT;
table.setLAyoutParams(params);
Edit:
TextView tView = new TextView(this);
LinearLayout.LayoutParams params = tView.getLayoutParams();
params.width = LayoutParams.FILL_PARENT;
params.weight = 1;
tView.setLayoutParams(params);
regards,
Aqif