I need to show the TextViews based on the info received from a server. E.g. I got 7 words from the server . I need to put every word in a different TextView to make it clickable. The textviews should fill the screen of the device from left to right in the lines. When the right border is reached then the next TextViews should be placed on the next line and so on.
The quantity of TextViews is variable and the words in the Textviews is different as well.
Create new textView instance and setLayoutparams to them.
Example,
TextView[] tx = new TextView[10];
TableRow[] tr = new TableRow[10];
for(i=0; i<10; i++) {
tx[i] = new TextView(this);
tx[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tx[i].setText("Data")
tr[i] = new TableRow(this);
tr[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tr[i].addView(tx[i]);
// and then adding table row in tablelayout
}
For your problem you can use single textview and set spannable string to the textview.
Within that string you can provide clicks you want.
I found the solution.
I won't put the whole code here. Only main parts.
There is vertical LinearLayout.
We need to calculate the width of the layout. I couldn't do it because I do all calculations before it is drawed.
I'm getting the screen width in dips:
Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float density = getResources().getDisplayMetrics().density;
float dpWidth = outMetrics.widthPixels / density;
int displayWidth = (int) dpWidth;
This is the free space available to put the Textviews.
Add LinearLayout to parent. Create a Textview and calculate the width:
// Calculate size of the button
Rect bounds = new Rect();
Paint textPaint = menuCategoryTV.getPaint();
textPaint.getTextBounds(text, 0, text.length(), bounds);
int width = bounds.width();
Then check if there is a room to place the Textview in the layout. To get it deduct TextView's width from available free space on the screen. Of course there is a space for the first textView. Until your TextView is not very long. But after filling up the layout by TextViews there will be no room for new elements. Create new LinearLayout, add it to parent and reset availble room to initial value.
Related
I'm using a TableLayout to create a square gameboard in Android. I want to set the dp of the table's width and height, and have its contents automatically expand and contract to fit the table.
I got this working with the entries in the tableRows as LinearLayouts with a single ImageView inside, but I need to change what images are displayed with click actions, so I thought I would use a ViewFlipper.
Now that I'm using the ViewFlipper, though, my image sizes have gone all wonky. Does anyone know if there's a setting I can set on ViewFlipper to get the images to auto adjust their size in a table?
Here's my xml:
<TableLayout
android:id="#+id/gameBoard"
android:layout_width="#dimen/boardWidth"
android:layout_height="#dimen/boardWidth"
android:layout_margin="0dp"
android:padding="0dp"
android:shrinkColumns="*"
android:stretchColumns="*" >
</TableLayout>
And here's the code I'm programmatically creating the table with:
TableLayout gameBoard = (TableLayout) findViewById(R.id.gameBoard);
TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
rowParams.setMargins(0, 0, 0, 0);
for (int y = settings.getBoardSide() - 1; y > -1; y--) {
TableRow row = new TableRow(this);
row.setPadding(0, 0, 0, 0);
for (int x = 0; x < settings.getBoardSide(); x++) {
ViewFlipper flipper = new ViewFlipper(this);
flipper.setOnClickListener(new TileClick());
//default image
ImageView cloud = new ImageView(this);
cloud.setImageResource(R.drawable.transparent_cloud);
cloud.setAdjustViewBounds(true);
flipper.addView(cloud, 0);
//second image
ImageView landscape = new ImageView(this);
landscape.setImageResource(R.drawable.land_scape);
landscape.setAdjustViewBounds(true);
flipper.addView(landscape, 1);
row.addView(flipper);
}
gameBoard.addView(row, rowParams);
}
It turned out that for my purpose a FrameLayout with its width and height set to a specific dp was best. That way I can control the view and ensure it has the right height and width. With the FrameLayout I can add and remove views at will, and layer different views on top of each other as well.
Alright I'm trying to build an activity that has a horizontal scrollview, that the user can swipe through, to view different "pages". My train of thought is these "pages" will be views. The following is a mockup of my idea (to mess around to see if it works)
I've experimented with this as follows:
My content view is set to the the scrollview. (unsure if this is an incorrect approach)
I create the scrollview, and place a view into it as follows:
private void setupScrollView()
{
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);
float density = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth = outMetrics.widthPixels / density;
int width = (int)MeasureUtils.convertDpToPixel(dpWidth, getApplicationContext());
int height = (int)MeasureUtils.convertDpToPixel(dpHeight, getApplicationContext());
_scrollView = new HorizontalScrollView(getApplicationContext());
_scrollView.setBackgroundColor(Color.CYAN);
_scrollView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Log.i("DEBUG", "Screen dp width = " + dpWidth + " screen dp height = " + dpHeight);
TextView view = new TextView(getApplicationContext());
view.setBackgroundColor(Color.RED);
view.setText("TEST");
view.setX(0); // Start at the left of the scrollview.
view.setWidth(width); // Size it so that it fills to the right of the scrollview.
TextView view2 = new TextView(getApplicationContext());
view2.setBackgroundColor(Color.GREEN);
view2.setText("TEST2");
view2.setX(width); // Start the second "page/view" offscreen to the right where i can scroll to it
view.setWidth(width); // Fill the screen width
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setBackgroundColor(Color.MAGENTA);
layout.addView(view);
layout.addView(view2);
_scrollView.addView(layout);
}
The idea above is that I will see a view, that takes up the screen, representing a page. This view should be "RED" in color. I can then scroll horizontally to the right and see the second view (view2) representing the next page. This view should be "GREEN" in color. This does not happen. I end up seeing what looks like 1/3rd or 1/2 of my screen being view1, the linearlayout taking up almost the whole screen (a bit of a gap to the right edge where the CYAN from the scrollview bleeds through).
Am I approaching this the wrong way, and/or is it possible to make this work the way I'm going at it?
You probably do not want to use a horizontalscroll view to create "pages".
Try looking at PageViewer
This automatically builds in all the sywpe and inflating logic for you.
Basically you will get a call to inflate a certain page. There you can then create your view (dynamically if you wish) and then just return the root to be rendered.
Alright I've figured out what I was doing wrong, and it turned out to be something very small...
The complete code is here:
private void setupScrollView()
{
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);
float density = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth = outMetrics.widthPixels / density;
int width = (int)MeasureUtils.convertDpToPixel(dpWidth, getApplicationContext());
int height = (int)MeasureUtils.convertDpToPixel(dpHeight, getApplicationContext());
_scrollView = new HorizontalScrollView(getApplicationContext());
_scrollView.setBackgroundColor(Color.CYAN);
_scrollView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Log.i("DEBUG", "Screen dp width = " + dpWidth + " screen dp height = " + dpHeight);
TextView view = new TextView(getApplicationContext());
view.setBackgroundColor(Color.RED);
view.setText("TEST");
view.setX(0);
view.setWidth(width);
view.setHeight(height - 50);
TextView view2 = new TextView(getApplicationContext());
view2.setBackgroundColor(Color.GREEN);
view2.setText("TEST2");
view2.setX(0);
view2.setWidth(width);
view2.setHeight(height - 50);
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setBackgroundColor(Color.MAGENTA);
layout.addView(view);
layout.addView(view2);
_scrollView.addView(layout);
}
This creates a horizontal scrollview programmatically, as I had, but the problem was that I was setting the second view to be "width" away, when it should be set to "0"as can be seen by:
view2.setX(0);
With that, I get 2 "views" that resemble pages in my scrollview that I can swipe through. Each taking up the whole page.
Hate having the code close and it being a simple fix that I missed :|
Hope this helps anyone else that tries to do it this way. I'm going to look into the PageViewer as Frank suggested.
I was wondering how I could "randomly" place an array of Buttons in a RelativeLayout?
Is it possible to space the buttons around the entire view?
Thanks for your help! I tried using setX() and setY() but they are float numbers and I'm unsure how they place the buttons in proportion to the size of the screen.
You can add layout margins to your buttons. As margins will be interpreted not relative to each other but to the frame, it will in fact position your buttons.
To set the margins you have to set the view's layout params:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
Random random = new Random();
params.leftMargin = random.nextInt(100);
params.topMargin = random.nextInt(100);
button.setLayoutParams(params);
However this may cause your buttons to overlap, or be outside the Activity, so it's best not to use entirely random values for positions but to perform checks for overlapping and set random ranges according to the device resolution and button size.
To get device display size:
Display display= activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int Height = display.getHeight();
instead do something like this first create a button array and find the respective id...
LayoutParams lp = new LinearLayout.LayoutParams(widthOfButtons,LayoutParams.WRAP_CONTENT);
Button[] buttons;
for(int i=0; i<4; i++) { //suppose you have four buttons
{
String buttonID = "button" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i] = ((Button) findViewById(resID));
buttons[i].setHeight(yourvalue);
buttons[i].setWidth(yourvalue);
buttons[i].setLayoutParams(lp);
}
hope it works for your
here is the code that i am using to generate my view object:
// creates the seekBar
sBGauge = new SeekBar(this);
sBGauge.setMax(depthL - 1);
sBGauge.setMinimumWidth(150);
sBGauge.setId(2000 + i);
sBGauge.setOnSeekBarChangeListener(this);
reguardless of what i set the sBGauge.setMinimumWidth(); to it always appears to only be about 20 wide.
any thoughts?
thanks
Edit: to give some more info I am using this seekbar in between two textViews in a tablerow.
bump
#Amit Hooda your solution did not solve my problem but it did lead me down the right path to finding a solution.
What I had to do to fix this issue was to change from a dynamically created a TableRow to a LinearLayout within my TableLayout. I was then able to get my screen width and subtract out my textviews and then set my width of the seekbar with the resulting number.
// gets the width of the screen to set the seekbar width
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
width = width - 170;
LinearLayout lL = new LinearLayout(this);
// creates the seekBar
sBGauge = new SeekBar(this);
sBGauge.setMax(depthL - 1);
sBGauge.setId(2000 + i);
sBGauge.setLayoutParams(new LinearLayout.LayoutParams(width, 50, 1f));
sBGauge.setOnSeekBarChangeListener(this);
Try this
LayoutParams lp = new LayoutParams(150, 150);
sBGauge.setLayoutParams(lp);
you can change the value 150 and 150 according to your need.
I want to show a list of flights on a listview. And I want to have them all of them align. I have used a LinearLayout, with gravity and padding. But I want to reduce the space for the 4th column, so then I can do bigger the size of the text. I have tried to set the layout_weight of this element to 0 and all of the rest to 1. But it doesnt work. So far I have this
Any ideas?
If you are going to use ListView with a list of LinearLayout view's (I would go with a TableRow list put into a TableLayout), then I would suggest predefining the width of each column in percentage of the total space (i.e. how much of the screen would you allow the column to allocate). Something among the lines:
// basically you build your adapter here
LinearLayout.LayoutParams wrapWrapLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int[] columnWidths = new int[]{20, 20, 20, 20, 20};
ArrayList<LinearLayout> tableRows = new ArrayList<LinearLayout>();//this is the adapter
LinearLayout row = new LinearLayout(this);
//add a header
row.setLayoutParams(wrapWrapLinearLayoutParams);
row.setGravity(Gravity.CENTER);
row.setBackgroundColor(headerColor);
row.addView(makeTableRowWithText(headerForCol1, columnWidths[0]));
row.addView(makeTableRowWithText(headerForCol2, columnWidths[1]));
row.addView(makeTableRowWithText(headerForCol3, columnWidths[2]));
row.addView(makeTableRowWithText(headerForCol4, columnWidths[3]));
row.addView(makeTableRowWithText(headerForCol5, columnWidths[4]));
tableRows.add(row);
for(int i = 0; i < numberOfItemsInTheFlightsTable; i++) {
row = new LinearLayout(this);
row.setLayoutParams(wrapWrapLinearLayoutParams);
row.setGravity(Gravity.CENTER);
row.addView(makeTableRowWithText(col1Text, columnWidths[0]));
row.addView(makeTableRowWithText(col2Text, columnWidths[1]));
row.addView(makeTableRowWithText(col3Text, columnWidths[2]));
row.addView(makeTableRowWithText(col4Text, columnWidths[3]));
row.addView(makeTableRowWithText(col5Text, columnWidths[4]));
tableRows.add(row);
}
//util method
private TextView recyclableTextView;
public TextView makeTableRowWithText(String text, int widthInPercentOfScreenWidth) {
int screenWidth = getResources().getDisplayMetrics().widthPixels;
recyclableTextView = new TextView(this);
recyclableTextView.setText(text);
recyclableTextView.setTextColor(Color.BLACK);
recyclableTextView.setTextSize(20);
recyclableTextView.setWidth(widthInPercentOfScreenWidth * screenWidth / 100);
return recyclableTextView;
}
I mean, the trick is that you predefine the percentage of screen allocated by each column.
Do the following
LinearLayout LL1 containing the first 4 columns
LinearLayout LL2 containing the last column
RelativeLayout RL contains LL1 and LL2
You can now position LL2 to the right of the container
EDITED