I want to insert a few LinearLayouts, but it doesn't work like it should. It inserts just one, but it should insert more.
LinearLayout commentsContainer = (LinearLayout) findViewById(R.id.view_comment_container);
commentsContainer.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
commentsContainer.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 0; i < postView.commentLenght(); i++) {
Log.e("LENGTH", postView.commentLenght()+"x"+i);
LinearLayout commentContainer = new LinearLayout(PostViewActivity.this);
commentContainer.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
LinearLayout userContainer = new LinearLayout(PostViewActivity.this);
userContainer.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
userContainer.setOrientation(LinearLayout.VERTICAL);
commentContainer.setOrientation(LinearLayout.HORIZONTAL);
commentContainer.setPadding(25,0,0,0);
ImageView commentImage = new ImageView(PostViewActivity.this);
commentImage.setLayoutParams(new LinearLayout.LayoutParams((int) ((float) width / 6), (int) ((float) width / 6)));
commentImage.setImageBitmap(postView.getComment(i).getImage());
TextView commentText = new TextView(PostViewActivity.this);
commentText.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
commentText.setText(postView.getComment(i).getText());
TextView displayUserText = new TextView(PostViewActivity.this);
displayUserText.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
displayUserText.setText(postView.getComment(i).getDisplayName());
Log.d("TEXT", postView.getComment(i).getText());
Log.e("TEXT", displayUserText.getText()+"");
displayUserText.setTag(postView.getComment(i).getUsername());
displayUserText.setTextSize(12);
displayUserText.setTextColor(getResources().getColor(R.color.colorAccent));
userContainer.addView(commentImage);
userContainer.addView(displayUserText);
commentContainer.addView(userContainer);
commentContainer.addView(commentText);
commentsContainer.addView(commentContainer);
}
Another strange thing: the first Log.d is always the correct one, but the second one is always the same. What's the mistake?
This code can be greatly cleaned up by using XML resource files. As each of the comments takes the same form, the same layout can be used for each. You can fill different values into the layout as you desire. These can all be added to a ViewGroup within another layout.
Programmatically generating layouts is much more error prone and complex than using an XML layout.
Doing some reading into the Android official documentation is absolutely worth it! https://developer.android.com/guide/topics/ui/declaring-layout.html
Related
I want to add buttons to relative layout dynamically as per button and screen width as shown in image. Number of buttons is not fixed and width of button depends on the text which is set to the button.
I tried to achieve this using below code but that to not working fine as per my requirement.
Can anyone please help me ? Please help me through this.
RelativeLayout layout = (RelativeLayout) findViewById(R.id.genre_layout);
for(int i=0; i < genreList.size(); i++){
Button btn = new Button(MovieDetailsActivity.this);
btn.setText(genreList.get(i).getGenreName());
btn.setPadding(15, 5, 15, 5);
btn.setBackgroundColor(Color.parseColor("#FFFFFF"));
btn.setBackgroundColor(Color.parseColor("#80333333"));
LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
param.setMargins(5, 5, 5, 5);
if (i != 0){
int prevId = genreList.get(i).getGenreId();
param.addRule(RelativeLayout.RIGHT_OF, prevId);
}
btn.setLayoutParams(param);
btn.setId(genreList.get(i).getGenreId());
layout.addView(btn);
}
Try this
Display display=getWindowManager().getDefaultDisplay();
int width=display.getWidth();
btn.setWidth(width);
or if you have two buttons, do
Display display=getWindowManager().getDefaultDisplay();
int width=display.getWidth();
btn1.setWidth(width/2);
btn2.seTwidth(width/2);
Update
LinearLayout.LayoutParams paramz = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
0dp, 1.0f);
then btn.setLayoutParams(paramz);
I have the code to add buttons dynamically to linear layout. Just check out whether it helps you https://docs.google.com/document/d/1QA1tAIe601fZT2Dlp1A0qDuLD0U4IqKL3f_Crx1rtkE/edit?usp=sharing
Try this for adding dynamic buttons in relativelayout
RelativeLayout layout = (RelativeLayout)findViewById(R.id.slidingDrawerContent);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT );
for (int i=0; i<4; i++) {
Button btn = new Button(this);
btn.setId(i);
btn.setText("some_text");
// lp.addRule(RelativeLayout.RIGHT_OF, <Id>);
layout.addView(tv2, lp);
}
I would like to suggest use LinearLayout as you asked in your question and give a Weight.
LinearLayout
I Solved my problem by using FlowLayout.
Sample code and references are available here
Its simple to use. Thank you all for help.
I'm currently programmatically adding RelativeLayout encapsulated in a Linearlayout. The base is a scrollview and i'm trying to add those layouts into scrollview named svbase
LinearLayout llbase = new LinearLayout(getApplicationContext());
LinearLayout.LayoutParams llbaseParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // Verbose!
llbaseParams.setMargins(0, new CommonOpearation().getPixel(10, getApplicationContext()), 0, new CommonOpearation().getPixel(10, getApplicationContext()));
llbase.setLayoutParams(llbaseParams);
llbase.setGravity(Gravity.CENTER_HORIZONTAL);
for(int n =0;n<2;n++)
{
RelativeLayout rLayoutBase = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams rLayoutParms = new RelativeLayout.LayoutParams( new CommonOpearation().getPixel(140, getApplicationContext()), new CommonOpearation().getPixel(125, getApplicationContext()));
**rLayoutParms.setMargins(0, 0, new CommonOpearation().getPixel(5, getApplicationContext()), 0);**
rLayoutBase.setLayoutParams(rLayoutParms);
Drawable drawable = MyCurrentActivity.this.getApplicationContext().getResources().getDrawable(R.drawable.curved_bg); //new Image that was added to the res folder
try {
rLayoutBase.getClass().getMethod(android.os.Build.VERSION.SDK_INT >= 16 ? "setBackground" : "setBackgroundDrawable", Drawable.class).invoke(rLayoutBase, drawable);
} catch (Exception ex) {
}
llbase.addView(rLayoutBase);
}
svBase.addView(llbase);
As you can see I have two relativelayout encapsulated in the linearlayout with a horizontal orientation. I've tried giving margin to each of the relativelayout using setMargin with a right of certain 5dp. However it does not gives margin inbetween the two relativelayout. It worked if I were to do in manually in xml though.
The differences can be seen at the image. the top is a xml specify layout while the bottom two relativelayout are generated programmatically
solved my own.
The solution is already out there! did not google enough! my fault!
Relative Layout ignoring setMargin()
I'm a newbie to Android development, and I'm very much still learning Java too so be gentle!
I am creating an app that can take information about a task (I'm basing it around a sort of homework planner), store that info and then display it in a list. The program must be able to dynamically generate the list from the background files. I have managed all of this so far, but when I create a basic output for each task, containing the "subject" and "details" variables using a LinearLayout they appear on the screen overlapping. They all seem to be creating correctly, but they are all being put in the same place. Are there attributes I can set to make them display in a vertical list???
Here is the piece of code where I generate the viewgroups and display them. This is called from a loop in another part of the program which finds the number of files in internal storage.
TextView subjView;
TextView detailView;
RelativeLayout displayLayout;
LinearLayout taskDisplay = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
subjView = new TextView(this);
detailView = new TextView(this);
displayLayout = (RelativeLayout) findViewById(R.id.relative_display_layout);
subjView.setText(subject);
detailView.setText(details);
layoutParams.setMargins(0, 0, 0, 0);
taskDisplay.addView(subjView, layoutParams);
layoutParams.setMargins(10, 0, 0, 0);
taskDisplay.addView(detailView, layoutParams);
displayLayout.addView(taskDisplay);
If I understand correctly, I think your issue is only that you are declaring and then changing the layoutParams margins which sets them both to the same, which is overlapping your TextViews.
Edit
Okay, I am still not 100% sure how you are doing all of this so my example may need to be tweaked. I tried to throw this together quickly so forgive me for any minor mistakes.
New mock up for dynamic layouts:
TextView subjView, detailView;
RelativeLayout displayLayout, rl;
// I am assuming this is your main layout
displayLayout = (RelativeLayout) findViewById(R.id.relative_display_layout);
// Just using a for loop as an example of a loop event, not sure how you are accomplishing this
for(int i = 0; i < data.length(); i++) {
RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, 100);
if (i > 0) {
int rePositionRule = i;
rllp.addRule(RelativeLayout.BELOW, rePositionRule);
}
RelativeLayout taskDisplay = new RelativeLayout(this);
taskDisplay.setLayoutParams(rllp);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, 0, 0, 0);
LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams2.setMargins(10, 0, 0, 0);
subjView = new TextView(this);
detailView = new TextView(this);
subjView.setText(subject);
subjView.setLayoutParams(layoutParams);
detailView.setText(details);
detailView.setLayoutParams(layoutParams2);
taskDisplay.addView(subjView);
taskDisplay.addView(detailView);
displayLayout.addView(taskDisplay);
}
Your displayLayout is a relativeLayout.. A relative layout, as the name implies, places element relative to each other. Normally you'd say "element A should go below element B" etc. Since you aren't providing any of these rules for the items you are creating they are just going to all go to the default position in a relative layout (which is the top of the screen.. hence the overlap)
If you don't want to deal with the hassle of changing your code to place things relatively simply switch your displayLayout to a LinearLayout in your xml and code and set its orientation to vertical. You'll probably want to wrap that in a scroll view if it runs off the screen
However, it sounds like what you really want is a ListView...
I need do design programatically one activity with 6 buttons (same size h and w), and all buttons show a fullsize of activity.
I tried do this: RelativeLayout with buttons and modify for tests.
Show one button!!!
`
setContentView(R.layout.main);
ArrayList<Button> buttons = new ArrayList<Button>();
//RelativeLayout bg = (RelativeLayout) findViewById(R.layout.main);
for (int i = 0; i < 10; i++) {
Button newButton = new Button(this);
newButton.setId(100 + i + 1); // ID of zero will not work
newButton.setText("XXXX");
buttons.add(newButton);
// New layout params for each button
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
if (i > 0) {
// using getId() here in case you change how you assign IDs
int id = buttons.get(i - 1).getId();
lp.addRule(RelativeLayout.RIGHT_OF, id);
}
this.addContentView(newButton, lp);
}`
please look this line if ok: this.addContentView(newButton, lp);
Thanks!!!
mateus
It's a bit not clear from your question whether you want all buttons to distribute evenly across the activity space or each button to take over all activity space?
In first case what you need is a LinearLayout with layout_weight for buttons set to 1.
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.weight = 1;
In the second case I think it's better to use a FrameLayout and just let buttons take over all space by setting
FrameLayout.LayoutParams.FILL_PARENT
to both dimensions.
First off I am new to android development and some seemingly easy tasks are frustrating me to no end. This is a follow on question to what was answered here: Changing the checkbox size in Android 2.0
The gist of it is that for some reason there is this extra space that keeps showing up next to my checkboxes (See Below).
Now I have tried to set the width to 1 and it doesn't get any shorter than what is shown. I have tried to set the width bigger and I can make the size bigger, but no shorter.
Please take a look at the code below and let me know what you see.
TableLayout table = (TableLayout) findViewById(R.id.timeEntriesTable);
for (int i = 0; i < timeEntries.getLength(); i++)
{
Element element = (Element) timeEntries.item(i);
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
CheckBox box = new CheckBox(this);
box.setButtonDrawable(getResources().getDrawable(R.drawable.checkbox_off_background));
box.setPadding(0,0,0,0);
box.setWidth(1);
box.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox box = (CheckBox) v;
if (box.isChecked())
{
box.setButtonDrawable(getResources().getDrawable(R.drawable.checkbox_on_background));
}
else
{
box.setButtonDrawable(getResources().getDrawable(R.drawable.checkbox_off_background));
}
}
});
TextView dateBox = new TextView(this);
String dateText = element.getAttribute("date");
dateBox.setText(dateText);
dateBox.setTextColor(Color.BLACK);
TextView customerBox = new TextView(this);
String customerName = element.getAttribute("customer");
customerBox.setText(customerName);
customerBox.setTextColor(Color.BLACK);
TextView hoursBox = new TextView(this);
String hours = element.getAttribute("hours");
hoursBox.setText(hours);
hoursBox.setTextColor(Color.BLACK);
TextView test = new TextView(this);
test.setTextColor(Color.RED);
test.setText("Test");
tr.addView(box);
tr.addView(dateBox);
tr.addView(customerBox);
tr.addView(hoursBox);
table.addView(tr, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
Thank you in advance!
That looks suspiciously like the "Time Entries" header is in its own table cell in a header row and the column of checkboxes below it is matching the same width. (See how the right edge of the text lines up perfectly with the date below it?) Since the checkbox's layout_gravity is likely defaulting to TOP|LEFT, it's being positioned in the upper left of the cell.
Try altering either the header row or the layout_gravity of the checkboxes.
So after the input of the two other answerers #adamp and #Phobos. I stumbled across what worked for me.
How to set (Text)View attributes programmatically?
By adding this:
TableRow.LayoutParams lp = new TableRow.LayoutParams();
lp.width = 15;
lp.setMargins(3, 5, 0, 0);
lp.height = 15;
tr.addView(box, lp);
I was able to tweak that cell exactly how I wanted it. It was very strange to me that it wasn't growing the column of the cell it was growing the checkbox itself. This is because in Android there are no actual cells, it uses the views and their sizes to generate the table apparently.
I have came across no tutorials or anything that has you set the LayoutParams programmatically that way. Thank you for your help troubleshooting this!
Table Layouts naturally want to make all the cells the same size. If you want one, or more, to be different sizes then that takes additional parameters.
To shrink all the extra space in your cells add this to your table object
table.setShrinkAllColumns(true);
Or to just shrink the first column where your checkbox is
table.setColumnShrinkable(int columnIndex, boolean isShrinkable)