0

I'm having some troubles creating a relativeLayout programmatically.For better understanding I attached a picture below. The things with plus and minus are buttons, which should also be dynamically created and added to the layout. The values of tv4 and tv5 should increase/decrease accordingly to button presses.

What I have done so far:

1) creating the layout:

RelativeLayout rl = new RelativeLayout(this); rl.setId(i); rl.setBackgroundResource(R.drawable.bg); RelativeLayout.LayoutParams Lparams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); Lparams.addRule(RelativeLayout.BELOW, R.id.RL_default); Lparams.setMargins(3, 5, 3, 0); rl.setLayoutParams(Lparams); 

2) adding the tv1:

 Lparams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); Lparams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); Lparams.setMargins(10, 0, 0, 0); TextView txt = new TextView(this); txt.setTextColor(Color.parseColor("#FFFFFF")); txt.setId(x); txt.setTextSize(25); txt.setLayoutParams(Lparams); txt.setText(name); rl.addView(txt); 

3) adding the tv2:

 Lparams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); Lparams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); Lparams.addRule(RelativeLayout.BELOW, txt.getId()); Lparams.setMargins(10, 0, 0, 0); TextView txtS = new TextView(this); txtS.setId(y); txtS.setText("Test: "); txtS.setTextSize(22); txtS.setLayoutParams(Lparams); txtS.setGravity(Gravity.BOTTOM); txtS.setPadding(0, 0, 0, 20); rl.addView(txtS); 

4) now I want to create the first button:

 Button btnSminus = new Button(this); btnSminus.setId(btn1); btnSminus.setText("<"); btnSminus.setTextSize(20); Lparams= new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); Lparams.addRule(RelativeLayout.RIGHT_OF, txtS.getId()); btnSminus.setLayoutParams(Lparams); rl.addView(btnSminus); 

The problem is, the the button View seems to just disappear from the screen when the line Lparams.addRule(RelativeLayout.RIGHT_OF, txtS.getId()); is executed. What can be the reason?

enter image description here

1 Answer 1

2

My guess would be that it's because you set the width of txtS to match_parent, so the button gets pushed off the screen. You can fix that by changing that to wrap_content.

Sign up to request clarification or add additional context in comments.

1 Comment

was a really dumb mistake, thank you. The problem is gone. Just one more question: what must I do in my onPause() or onDestroy() method to get the dynamically added layout saved? Since it disappears after the app is restarted..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.