I need to add indeterminate number of textview to a view, and I would love if it can be auto adjust to the screen.
What I tried is to add horizontal LinearLayouts to a vertical parent LinearLayout, but this way I can add maybe 2 items or 3 per line but it doesn't have this unordered effect.
Is there any way to achieve this?
What i suggest is to not create dynamically a horizontal layout (if you are doing that).
instead you can create a horizontal layout resource like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight="1"
android:text="ONE" />
<TextView
android:id="#+id/end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:text="TWO" />
</LinearLayout>
And then in your main activity do like this:
for(i in 0..2) {
val view: View?
val inflater =
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
view = inflater.inflate(R.layout.horizontal, null)
val textOne = view.findViewById<TextView>(R.id.start)
textOne.text = "TEST $i"
val textTwo = view.findViewById<TextView>(R.id.start)
textTwo.text = "TEST $i"
(mainL as LinearLayout).addView(view)
}
Where mainL is main vertical layout, to which you can add padding, or you can modify your horizontal one, it depends on what you want to achive.
In this example i used a for loop just to show you that 3 lines are created, in every cicle if you have a list of text to put in you could use this syntax for loop
for ((index, value) in names.withIndex()) {
println("$index: $value")
}
reference: https://kotlinlang.org/docs/tutorials/kotlin-for-py/loops.html
For your specific case i suggest to have the main layout with padding start and end, and in horizontal layout margin top and bottom to create space between elements.
If you want to use LinearLayouts, you can go into your xml and add only a Vertical LinearLayout.
After this, you can add Horizontal LinearLayouts for your rows, to which you'll add cells, TextViews in your case.
In the "OnCreate" I'm only getting the Views and calling the methods used to add rows and cells to specified row.
public class MainActivity extends AppCompatActivity {
/**
* #verticalLayout
* Contains the rows of your String matrix
*/
LinearLayout verticalLayout;
/**
* #rowCellDivisor
* Contains the horizontal layout of each row
*/
LinkedList<LinearLayout> rows;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
verticalLayout = findViewById(R.id.verticalLayout);
addRow();
addRow();
addRow();
addRow();
addTextViewToRow(0);
addTextViewToRow(0);
addTextViewToRow(0);
addTextViewToRow(1);
addTextViewToRow(1);
addTextViewToRow(2);
addTextViewToRow(2);
addTextViewToRow(2);
addTextViewToRow(2);
addTextViewToRow(2);
}
There we create a row, which is nothing more than a LinearLayout with Horizontal orientation.
private void addRow(){
LinearLayout row
= new LinearLayout(
getApplicationContext()
);
row.setOrientation(LinearLayout.HORIZONTAL);
row.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
verticalLayout.addView(row);
}
This creates the TextView to add in the specified row.
private void addTextViewToRow(int rowAtPosition){
TextView textView = new TextView(getApplicationContext());
textView.setText("StartLongTextaaaaaaaaaaaaaaaaaaaaaaaa" +
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" +
"ccccccccccccccccccccccccccccccLongTextEnd");
/**
* Third entry for params is for weight, so that you can
* decide how much space the cell will occupy in the row
* when there will be more than one view in the same row.
*/
LinearLayout.LayoutParams layoutParams
= new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
1f
);
/**
* setMargins e.g. between cells of the row and screen
* borders
*/
layoutParams.setMargins(25, 0, 25, 25);
textView.setLayoutParams(
layoutParams
);
LinearLayout view = (LinearLayout)
verticalLayout.getChildAt(rowAtPosition);
view.addView(textView);
}
}
Related
I have a simple view:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/contact_selected"
android:layout_marginTop="10dp"
android:layout_marginEnd="5dp"
android:orientation="horizontal"
android:padding="3dp">
<TextView
android:id="#+id/txt_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Billy Bob"
/>
</LinearLayout>
When I statically copy the LinearLayout markup into my main activity layout, the margins are as expected. However, when I add the view into the main activity layout dynamically, the margins are ignored. Here's how I insert the view
LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.test, null);
TextView txt_title = (TextView)view.findViewById(R.id.txt_title);
txt_title.setText("Dynamic #1");
llayout.addView(view, llayout.getChildCount()-1);
View view2 = inflater.inflate(R.layout.test, null);
txt_title = (TextView)view2.findViewById(R.id.txt_title);
txt_title.setText("Dynamic #2");
llayout.addView(view2, llayout.getChildCount()-1);
Here's what it looks like:
The container in the main layout is a LinearLayout, which is a child of a HorizontalScrollView. Any insight is appreciated.
When dynamically adding views, you shouldn't inflate the View with a null ViewGroup parent. So, in other words you should be using inflater.inflate(R.layout.test, linearLayout, false);. The parent is used when determining what type of layout parameters to generate. Pass your parent container (in this case, your linear layout), so it correctly instantiates the ViewGroup.MarginLayoutParams from your XML.
This happens because you need to give "Margin" to layouts dynamically. You can do this by creating an object of "LayoutPrams", like this:-
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
Here , you can set the LayoutParams to the linearlayout:
ll.addView(okButton, layoutParams);
Hope it helps.
First, you have to get display density.
related docs are https://developer.android.com/reference/android/util/DisplayMetrics.html
and get ID which you want set margin view.
for my case,
layout_login_box = (ConstraintLayout)findViewById(R.id.login_layout_box);
float density = getResources().getDisplayMetrics().density;
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams)layout_login_box.getLayoutParams();
params.setMargins((int) (24 * density),0,(int) (24 * density),(int) (16 * density));
layout_login_box.setLayoutParams(params);
Also, you can change ConstraintLayout to your own view.
Have 2x2 grid(Dynamic using TableLayout) need to show image on that. now based on image size, means-- if image fit for 1 cell means 1 cell,else big means 2 cells or 4 cells based on size( I know how many cells it will occupy)
i can show image in 1 cell, but problem is if image need 2 cells(1st column) how can show image in 2cell(With out disturbing the grid)
Without disturbing the grid, the workaround I see is to dynamically set image on top of your TableLayout.
Then you can archive this:
I've uploaded the code of the test project here;
You initialize overlappingImage and once you need to set image to your cell - you just add it to the layout and setting height and width params based on number of cells you want to fill.
TableLayout generates dynamically, the cell's layout xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<View
android:layout_margin="4dp"
android:background="#aacc00"
android:layout_height="40dp"
android:layout_width="40dp"/>
</FrameLayout>
The Activity's layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container"
android:padding="16dp"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="280dp"/>
<LinearLayout
android:id="#+id/buttonsLinearLayout"
android:layout_below="#+id/tableLayout"
android:layout_marginTop="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:text="1x1"
android:id="#+id/button11"
android:onClick="onClick11"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="4x1"
android:id="#+id/button21"
android:onClick="onClick41"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="2x3 at (2;2)"
android:id="#+id/button12"
android:onClick="onClick32"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="2x2"
android:id="#+id/button22"
android:onClick="onClick22"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
And the Activity code to handle button clicks & generates table:
public class MainActivity extends AppCompatActivity {
RelativeLayout container;
int cellWidth = 0, cellHeight = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
tableLayout.setStretchAllColumns(true);
for (int i = 0; i < 4; i++) {
TableRow tableRow = new TableRow(this);
for (int j = 0; j < 10; j++) {
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View cell = layoutInflater.inflate(R.layout.table_cell, null, false);
if (cellHeight == 0 ) {
cell.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
cellWidth = cell.getMeasuredWidth();
cellHeight = cell.getMeasuredHeight();
}
tableRow.addView(cell);
}
tableLayout.addView(tableRow);
}
container = (RelativeLayout)findViewById(R.id.container);
overlappingImage = new ImageView(this);
overlappingImage.setScaleType(ImageView.ScaleType.FIT_XY);
}
ImageView overlappingImage;
private void restoreTableLayout() {
container.removeView(overlappingImage);
}
public void onClick11(View view) {
restoreTableLayout();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(cellWidth, cellHeight);
overlappingImage.setLayoutParams(params);
overlappingImage.setImageResource(R.drawable.horizontal_cat);
container.addView(overlappingImage);
}
public void onClick41(View view) {
restoreTableLayout();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(cellWidth*4, cellHeight);
overlappingImage.setLayoutParams(params);
overlappingImage.setImageResource(R.drawable.horizontal_cat);
container.addView(overlappingImage);
}
public void onClick32(View view) {
restoreTableLayout();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(cellWidth*3, cellHeight*2);
params.setMargins(cellWidth*2, cellHeight*2, 0 ,0);
overlappingImage.setLayoutParams(params);
overlappingImage.setImageResource(R.drawable.vertical_cat);
container.addView(overlappingImage);
}
public void onClick22(View view) {
restoreTableLayout();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(cellWidth*2, cellHeight*2);
overlappingImage.setLayoutParams(params);
overlappingImage.setImageResource(R.drawable.horizontal_cat);
container.addView(overlappingImage);
}
}
I hope, it helps.
Create separate layout files for rows that would need one cell and two cell as follows:
one_cell_table_row.xml (Notice the android:layout_span="2" for the ImageView
<?xml version="1.0" encoding="utf-8"?>
<TableRow
android:background="#drawable/bg_gray"
android:layout_marginTop="5dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/imgMyImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_span="2" />
</TableRow>
two_cell_table_row.xml (The TextView placed just as a placeholder for the second cell) (No layout_span required here as in the above layout)
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/imgMyImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_weight="1"
android:text="..."
android:textColor="#767575"
android:id="#+id/txtJustAPlaceholder"
android:textSize="14dp" />
</TableRow>
Note: The id for the ImageView to be kept same in both layout for the java code below to work correctly.
The above is assuming your grid is 2x2. If your grid size is different create more layout for each kind of row you want and add extra conditions in the java code below.
Adding the TableRow with the right layout inflated:
Then programatically determine which layout needs to be inflated. Inflate the required layout for table row and add it to your table layout:
Following code is assuming that you are using a fragnemt. If you are doing directly in an activity replace code to work for Activity accordingly.
TableLayout table = (TableLayout) getView().findViewById(R.id.youtTableLayout);
if(<your image size needs two cells>) {
TableRow row = (TableRow) LayoutInflater.from(getActivity().getApplicationContext())
.inflate(R.layout.two_cell_table_row, null);
}
else if(<your image size needs one cell) {
TableRow row = (TableRow) LayoutInflater.from(getActivity().getApplicationContext())
.inflate(R.layout.one_cell_table_row, null);
}
...
...
// add more conditions and respective layouts as you need.
...
...
ImageView myImgView = (ImageView) row.findViewById(R.id.txtCrdSectionHeader);
// set the image for your image view here.
table.addView(row);
table.requestLayout();
Again, the above was assuming that your TableLayout has a 2x2 grid. If you plan to use a different one, update the layout files for TableRows we created above accordingly or set them dynamically using your java code.
You can calculate the image size and the screen size at runtime.Based on the calculations you can set the table properties at runtime. For example if the image is going to take two columns set the span property on that row programmatically.
I would suggest for your requirement you can consider creating the layout in code itself-rather than using any xml.
You can also have a look at Recycler view. It has more powerful ways to control the layout of the children. Have a look at this video-Mastering Recycler View -It is trying to do similar thing what you are looking for.
I am working on an Android project and I have an issue with the layout.
What I have is a JSONArray that I loop round inflating a new TableRow and within the loop round another array within the JSON array to populate it with fields. The fields are populated by inflating an XML file and adding this view to the table row. However, at the moment nothing shows up in the row.
Below is my TableRow XML file:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"/>
Below is my TextView XML:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/black"
android:padding="5dp"/>
Below is how I am populating the TableRow and the TextView:
for (int i = 0; i < result.length(); i++) {
final TableRow tr = (TableRow) getLayoutInflater(getArguments()).inflate(R.layout.result_table_row_light_theme, resultTable, false);
if (i == 0) {
tr.setBackgroundColor(getResources().getColor(R.color.appPrimaryColour));
} else if (i % 2 == 0) {
if (settings.getInt(Defines.SharedPreferenceSettings.APPLICATION_THEME,
com.BoardiesITSolutions.Library.R.style.LibAppTheme) == com.BoardiesITSolutions.Library.R.style.LibAppTheme) {
tr.setBackgroundColor(getResources().getColor(R.color.resultRowLightThemeAlternateRow));
}
}
JSONArray array = result.getJSONArray(i);
for (int j = 0; j < array.length(); j++) {
final TextView textView;
textView = (TextView) getLayoutInflater(getArguments()).inflate(R.layout.result_textview, tr, false);
textView.setText(array.getString(j));
if (i == 0) {
textView.setTypeface(null, Typeface.BOLD);
textView.setGravity(Gravity.CENTER_HORIZONTAL);
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tr.addView(textView);
}
});
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
resultTable.addView(tr);
}
});
}
If I change my TextView XML file so that the layout_width is wrap_parent instead of 0dp then everything is shown on the screen.
However, when the textview is 0dp and the layout_weight is 1 then nothing is displayed, however I would have expected each text view to be evenly distributed across the width of the screen to fill the space.
What I should probably mention, don't know if it makes a difference, is the TableView is within a HorizontalScrollView. The row should fit in the width of the screen, if the data is smaller than the screen, but if the row won't fit, then the view will be horizontally scrollable.
UPDATE 1
Below is the XML that hosts the TableLayout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="horizontal">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout android:id="#+id/resultTable"
android:stretchColumns="*"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TableLayout>
</HorizontalScrollView>
</LinearLayout>
</ScrollView>
</RelativeLayout>
What I should probably mention, don't know if it makes a difference, is the TableView is within a HorizontalScrollView.
It is a logical error to tell a child view inside a scrolling container to match_parent or fill the available space in any way. A scrolling container, like ScrollView or HorizontalScrollView measures its one-and-only child view as UNSPECIFIED so that the child can grow beyond the parent bound in that one direction (and, thus, be scrollable).
The child of a scrolling container is not given what the "available space" would be for it to fill, and operations like layout weight have no effect if the parent's dimension is not well-defined.
The row should fit in the width of the screen, if the data is smaller than the screen, but if the row won't fit, then the view will be horizontally scrollable.
The functionality you are looking for is fillViewport (docs link), which tells the scrolling container to force the child to match it's size if the measured width (in the horizontal case) is less than the parent. Use this in place of applying a weight.
Try this :
public void createTextView(Context context, LinearLayout parent) {
final TextView v = new TextView(context);
parent.addView(v); // Mandatory!
v.post(new Runnable() { // In UI Thread. View Must be added to parent before getting layout params!
#Override
public void run() {
// Get params:
LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) v.getLayoutParams();
// Set only target params:
lParams.width = 0;
lParams.weight = 1;
v.setLayoutParams(lParams);
}
});
}
Can you try to do your layout in XML (just to debug it, with dummy data)? Does it work as expected?
The docs mention that:
children of a TableRow do not need to specify the layout_width and layout_height attributes in the XML file. TableRow always enforces those values to be respectively MATCH_PARENT and WRAP_CONTENT.
Not sure if that means that it'll also mess stuff up if you try to set these values. As you've found, it's clearly not just ignoring them if they are set.
The other part says that the parent of the TableRow should be a TableLayout - is that the type of resultTable (you mentioned TableView) - otherwise it will behave as a LinearLayout with horizontal orientation.
I have to split a Single Linear layout into a Two Columns(Like newspaper Columns).The linear layout contain text-view and image-view
I have taken the screen width and have divided it to half and made the TextView and ImageView to come in a first column , ie, A B C blocks in the picture below.. now the remaining TextView and 'ImageView has to go to next column like in D E F like that it goes on.So it would be helpful if anyone gives me any code or ideas to implement this.. I tried with GridView which is not suitable for my issue. Since the TextView and ImageView sizes are not definite.
I don't know how to split Liner layout.
I tried with calculating the rootlayout height
like this
linearLayout.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
int linsize=linearLayout.getHeight();
int relsize=root.getHeight();
int textsize=txt1.getHeight();
mainheight=relsize;
subheight=linsize;
Toast.makeText(getApplicationContext(), "Linerlayout "+linsize, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Relative layout"+relsize, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "text height "+textsize, Toast.LENGTH_LONG).show();
if(mainheight==subheight)
{
Toast.makeText(getApplicationContext(), "make a new linear layout", Toast.LENGTH_LONG).show();
createsubview();
}
}
});
Screenshot
You could easily do this with nested LinearLayouts:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/item" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
<ImageView
content here/>
<TextView
content here/>
</LinearLayout>
</LinearLayout>
Then all that you need to do is put A, B and C in the first vertical layout, and D, E and F in the second.
You can't do it with GridView. You would have to create a custom view to do this.
if you know how big your grid items are, you can cut some corners. GridView is complicated mostly because it deals with items of any size and loads them dynamically. An easier way for you might be:
1.Create a HorizontalScrollView with a horizontal LinearLayout inside.
2.Determining how many rows of your item will fit on the screen. Call this rows.
3.while you still have items you need to layout:
1.Create a vertical LinearLayout, adding rows or less items to it.
2.Add your new vertical LinearLayout to the horizontal one.
There are some downsides versus what a "horizontal GridView" would get you:
1.All the views are loaded up immediately, which is bad for huge lists of items.
2.You need to know how big your items are, and they need to be the same size.
Upsides:
1.It's very easy to implement.
for more inf plz see this link
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView scrollView = new ScrollView(this);//ScrollView
LinearLayout ll = new LinearLayout(this); //root LinearLayout
ll.setOrientation(LinearLayout.HORIZONTAL);//with horizontal orientation
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT,1f);
LinearLayout l2 = new LinearLayout(this); //sub linearlayout
l2.setOrientation(LinearLayout.VERTICAL);//with vertical orientation
l2.setLayoutParams(layoutParams);
LinearLayout l3 = new LinearLayout(this); //sub linearlayout
l3.setOrientation(LinearLayout.VERTICAL);//with vertical orientation
l3.setLayoutParams(layoutParams);
int totalvalues=41; //i take count as 41
for(int i=0;i<totalvalues;i++){ // add the buttons in the layout based on condition
Button okButton=new Button(this);
okButton.setText("Button"+i);
if(i<=totalvalues/2){
l2.addView(okButton);
}
else{
l3.addView(okButton);
}
}
ll.addView(l2); //add sub linearlayout to root linearlayout
ll.addView(l3); //add sub linearlayout to root linearlayout
scrollView.addView(ll); //add the root linearlayout to scrollview
setContentView(scrollView);
}
Have you tried:
DisplayMetrics metrics = getResources().getDisplayMetrics();
float dpW = 0f;
int pixelsW = (int) (metrics.density * dpW + 0.5f);
TableLayout.LayoutParams lp = new TableLayout.LayoutParams(pixelsW, LayoutParams.WRAP_CONTENT, 1f);
TextView txt = new TextView(MainActivity.this);
ImageView img = new ImageView(MainActivity.this);
txt.setLayoutParams(lp);
img.setLayoutParams(lp);
Using TableLayout's LayoutParams, you can set the weight of the view, which, as you know, must be 1. We also use DisplayMetrics to convert a float into the "dp" format used in xml.
EDIT:
You can also set this LayoutParams to a LinearLayout.
I need to move the content of the screen to the left, so I can make room for the slide menu on the right
Here is the code:
// modify content layout params
try {
content = ((LinearLayout) act.findViewById(android.R.id.content)
.getParent());
} catch (ClassCastException e) {
/*
* When there is no title bar
* (android:theme="#android:style/Theme.NoTitleBar"), the
* android.R.id.content FrameLayout is directly attached to the
* DecorView, without the intermediate LinearLayout that holds the
* titlebar plus content.
*/
content = (FrameLayout) act.findViewById(android.R.id.content);
}
FrameLayout.LayoutParams pr = (android.widget.FrameLayout.LayoutParams) content
.getLayoutParams();
pr.rightMargin = menuSize;
content.setLayoutParams(pr);
// add the slide menu to parent
parent = (FrameLayout) content.getParent();
try {
parent = (FrameLayout) content.getParent();
} catch (ClassCastException e) {
/*
* Most probably a LinearLayout, at least on Galaxy S3.
*/
LinearLayout realParent = (LinearLayout) content.getParent();
parent = new FrameLayout(act);
realParent.addView(parent, 0); // add FrameLayout to real parent of
// content
realParent.removeView(content); // remove content from real parent
parent.addView(content); // add content to FrameLayout
}
LayoutInflater inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
menu = inflater.inflate(R.layout.slidemenu, null);
FrameLayout.LayoutParams lays = new FrameLayout.LayoutParams(menuSize,
FrameLayout.LayoutParams.MATCH_PARENT, Gravity.RIGHT);
lays.setMargins(0, statusHeight, 0, 0);
menu.setLayoutParams(lays);
parent.addView(menu);
but what I get is:
the content is just resized to fit the screen, how can I make this work?
Btw I can't modify the content layout its a relative layout with a surfaceview, but it should work with any layouts because I modify the DecorView which is the top view container
To move the 'Screen' you'll need to call getLayoutParams() on the View, modify it as necessary and then call setLayoutParams() on the View.
But for a great tutorial to how to implement a slide in menu see here:-
http://android.cyrilmottier.com/?p=658
To add further help, here's a layout that achieve's what I think you're after:-
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue" >
</LinearLayout>
<LinearLayout
android:layout_width="200dip"
android:layout_height="match_parent"
android:layout_marginLeft="-100dip"
android:background="#color/grey_divider"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
This will result in the second LinearLayout appearing 50% off the left hand side of the screen. FYI the LinearLayout you're moving will need an absolute width. But you could define it to FILL_PARENT in your xml, and then get the width and set it to this as an absolute value in code the first time you set the margin to a negative value.
Hope this helps.
Use parent as liner layout, set weight for both left and right layouts view.
put your left view in horizontalScrollview which need to be scrolled out of screen.