سؤال

The problem is, I want to add TAGS (like the ones at the bottom of the post) to my screen view programatically. The amount will be unknown but in the range of 10 lets say. I know i can use a horizontal list view but i am not sure how and if it is even possible to wrap the not fitting tags to next line. I don't think it is possible. Next, using the Gridview is an option, but how is it possible to assign horizontal spaces to each tag, if they are of different lengths? Is there any way possible to list them in a row without knowing the amount and making them wrap to "next line" dynamically?

هل كانت مفيدة؟

المحلول

Recently I had to bare with something similar to what you're asking. I finally decided using a TableView, and construct the TableRows dynamically. That seemed nice, until I faced the problem of how to know when to add a new item to the existing TableRow or add the row to the TableView and start a new one.

A workaround (some may even call it a hack) that I particularly don't like but works is the following: Measure the width of your screen, using a code like this:

final Display display = getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);

final WindowManager.LayoutParams params = getWindow().getAttributes();

You'll be able to get the width of your screen within your params.width parameter. I mutiplied it by 0.95 to not strictly fit the rows, mainly because it might work incorrectly.

So now, you'll need to have a loop to process all the items you want to add, let's suppose they're TextViews. Keep the count of the width you've already added, and if the new item's width surpasses the width, add it to the next row.

totalwidth = 0;
for (TextView tv : myTVitems) {
  if (totalwidth + tv.getWidth() < parameters.width * 0.95) {
    // Add it to the existing row
    totalwidth += tv.getWidth();
  }
  else {
    // Add the `TableRow` to the `TableView` and start a new `TableRow`
    totalwidth = 0;
  }
}

I'm writing this from memory so it may not compile without any explicit cast, but that's the idea.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top