How to inflate Button to LinearLayout progmatically in this case? - android

My task is to generate several amount of buttons with fixed width and height.I decided to store these buttons in some ArrayList to use in the future. This is how I do it:
for(int i = 1 ; i<=n; i++)
{
Button place = new Button(this.context) ;
place.setTextColor(ContextCompat.getColor
(this.context,R.color.background_color));
place.setTypeface(typefaceForPlaces);
place.setId(i+0);
place.setBackgroundResource(R.drawable.real_place_background);
place.setLayoutParams(new
LinearLayout.LayoutParams(65,65));
places.add(place);
}
But problem is here
place.setLayoutParams(newLinearLayout.LayoutParams(65,65));
Here,width and height is set in pixels. But I need dp. I know code that
converts dp to pixels, but I do not think that it is good solution. Now,I have an idea to create some layout and store there my button's shape. Here is my layout for this called place_button.xml:
<?xml version="1.0" encoding="utf-8"?>
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/button_id"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/real_place_background"
android:textColor="#202020">
</Button>
And I created some View and inflated that button to this view. After that, I got the button above by its id and save it to another button,because I need a lot of such buttons. Then I needed to change new button's id. But i got following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.incubic.abay.clasico/com.incubic.abay.clasico.GameActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setId(int)' on a null object reference
Below is my code:
private void generatePlaces() {
View place_view = LayoutInflater.from(getContext()).inflate(R.layout.place_button,null);
for(int i = 1 ; i<=n; i++)
{
Button place = (Button)place_view.findViewById(R.id.button_id);
place.setId(i+0);
place.setTypeface(typefaceForPlaces);
places.add(place) ;
}
}
Everything happens in Fragment. generatePlaces method is called after onViewCreated. How to solve my problem?

Probably you have an issue due to absence of a Button id
<?xml version="1.0" encoding="utf-8"?>
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/button_id"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/real_place_background"
android:textColor="#202020"/>
UPDATE:
When you do inflation, you already get your Button view, no need to do findViewById.
In general I don't think inflating a view in your case is a good approach. Better create buttons:
private void generatePlaces()
{
for (int i = 1; i <= n; i++)
{
Button place = new Button(this.context);
place.setTextColor(ContextCompat.getColor(this.context, R.color.background_color));
place.setTypeface(typefaceForPlaces);
place.setId(i + 0);
place.setBackgroundResource(R.drawable.real_place_background);
place.setLayoutParams(new LinearLayout.LayoutParams(dpToPx(50), dpToPx(50)));
places.add(place);
}
}
private int dpToPx(int dp)
{
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}

I think it is because you change the id of the button, on the next iteration you get a null pointer exception. I'd say create button views programmatically entirely, not from an xml and then append those to the parent view. Or look into something like listviews.
I'd say go with your earlier approach and refer to this question for converting to DP.

Related

"Inteligent" resize on layout?

I'm having an issue working with layouts, I've a linear layout (could be a relative layout or a table layout) which will contain an undefined number of buttons when the activity is loaded. This means, the quantity of buttons will be determined when the activity is being created. The thing is, I'm trying to fit them all in one line (with a center gravity) without changing each buttons' width UNTIL one of them reaches the margin of the screen. In other words, I want the buttons JUST to resize when at least one of them reaches the margin of the screen. That is because, I can't determine the space they're going to use because they are not created.
My actual linear layout:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="#+id/linearLayout_1"
android:layout_above="#+id/linearLayout_2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="30dp"
android:orientation="horizontal"
android:gravity="center"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
</LinearLayout>
Piece of code that creates the buttons:
protected void hacerVisiblesRespuesta(){
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayout);
assert linearLayout != null;
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,40, getResources().getDisplayMetrics());
for(int i = 0; i < longuitudPalabra; i++){
String boton = "btn_rsp" + Integer.toString(i+1);
Button bt = new Button(this);
bt.setText("");
bt.setId(getResourceId(boton,"id",getPackageName()));
bt.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT
, height
, 1.0f));
bt.setTextColor(Color.BLACK);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickBotonRespuesta(v);
}
});
bt.setVisibility(View.VISIBLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
bt.setBackground(getDrawable(R.drawable.bgbtnrsp));
}else{
//bt.setBackgroundDrawable(getDrawable(R.drawable.bgbtnrsp));
}
bt.setTextSize(20);
Typeface typeFace= Typeface.createFromAsset(getAssets(),"fonts/Montserrat-Regular.ttf");
bt.setTypeface(typeFace);
linearLayout.addView(bt);
}
}
I've tried many things, one of them was to make the buttons' width variable with weight property. The thing is if there are a small quantity of buttons, lets say 4, their width ended up enormous. Is there any way to achieve this through code? Thanks.
have you tried this?
button.setLayoutParams (new LayoutParams(50, LayoutParams.WRAP_CONTENT)

Parse RelativeLayout, Set Content, And Add It To A LinearLayout

Ok... here's my situation.
I have a carousel of images in a HorizontalScrollView - which contains a LinearLayout - in my Activity, like so:
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/slider"
android:scrollbars="none" >
<LinearLayout
android:id="#+id/carousel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
/>
</HorizontalScrollView>
I have a TypedArray, loop through it, and on each run, set these images programatically, add a ClickListener and a Tag, and add this ImageView to the LinearLayout (set in my Activity Layout), like so:
// Get the array
final TypedArray carouselArray = getResources().obtainTypedArray(R.array.carousel_array);
// Populate the Carousel with item
for (int i = 0 ; i < carouselArray.length() ; ++i) {
// Image Item
ImageView outerImage;
// Set the image view resource
if(i == 0) {
outerImage.setImageResource(R.drawable.toy_filter_clear);
}
else {
outerImage.setImageResource(carouselArray.getResourceId(i, -1));
}
// Set Touch Listener
outerImage.setOnTouchListener(this);
final String prepend = "CAROUSEL_";
final String index = String.valueOf(i);
final String tag = prepend.concat(index);
outerImage.setTag(tag);
/// Add image view to the Carousel container
mCarouselContainer.addView(outerImage);
}
But now, I just found out that I have to programatically add a second image to sit inside/on top of the first image at particular coordinates (damn you UI ppl!). I need these to be considered the same image/view essentially, so need to pack them together inside of a layout, I am assuming. So I have made a layout file, like so:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/carousel_item"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/carousel_outer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/toy_filter_normal"
/>
<ImageView
android:id="#+id/carousel_inner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/carousel_outer"
android:layout_alignRight="#+id/carousel_outer"
android:layout_marginBottom="10dp"
android:layout_marginRight="5dp"
android:src="#drawable/thumb_nofilter"
/>
</RelativeLayout>
This has the proper positioning, and the default images set on it. So what I want to be able to do is to reach into the Layout file, grab the ImageViews by their ID, overwrite the image if necessary, and then add that RelativeLayout to my LinearLayout at the end of my loop... sounds easy enough, right ?
My first attempt was to do it like this :
RelativeLayout item = (RelativeLayout) findViewById(R.id.carousel_item);
ImageView outerImage = (ImageView) item.findViewById(R.id.carousel_outer);
ImageView innerImage = (ImageView) item.findViewById(R.id.carousel_inner);
... but that gives me a NullPointer on the ImageView...So then I tried to inflate the RelativeLayout first, like this:
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.carousel_item_layout, null);
ImageView outerImage = (ImageView) view.findViewById(R.id.carousel_outer);
ImageView innerImage = (ImageView) view.findViewById(R.id.carousel_inner);
This gets rid of the NPE's, and (apparently) let's the images be set properly like so:
if(i == 0) {
outerImage.setImageResource(R.drawable.toy_filter_clear);
innerImage.setImageResource(0);
}
else {
outerImage.setImageResource(R.drawable.toy_filter_normal);
innerImage.setImageResource(carouselArray.getResourceId(i, -1));
}
but when I try to add the outerImage ImageView back to the LinearLayout, I get an NPE there:
mCarouselContainer.addView(outerImage);
More to the point, I don't want to add ONLY the one ImageView to the LinearLayout/HorizontalScrollView - I want to somehow pack the resulting images back into the RelativeLayout and add the whole thing back into my LinearLayout... but, it is worth mentioning, that this also gives me an NPE.
What is a guy to do ? Any thoughts appreciated...
Ok... Wow, thanks SO Code Monkey!
I managed to fix this with a one line fix, by adding the inflated View to the LinearLayout instead of the ImageView or the RelativeLayout (which wasn't doing anything), like so:
mCarouselContainer.addView(view);
Don't know why I hadn't tried that before, but I was unclear on whether as it's children were being updated if it would reflect the parent, so to speak... now I know it was.
I'm gonna keep the question up, as I think it's helpful... ?

Android: ImageView, LinearLayout and TextView heights returned negative, 0 and 0, why?

I am trying to scale the image in my linear layout to fill the available space, but I don't understand the values I'm getting for the widths of the layout. Here's the relevant part of my main.xml layout file:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LeftButtonsLayout"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="10"
android:orientation="vertical" >
<TextView
android:id="#+id/Jump"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/jump"
android:textStyle="bold"
android:padding="5dip"
/>
<ImageView
android:id="#+id/JumpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="#drawable/jump"
android:contentDescription="#string/jump"
android:padding="5dip"
/>
<LinearLayout
Here's the onCreate() method of my activity, which has a debug print:
public void onCreate (Bundle savedInstanceState) {
setContentView(R.layout.main);
LinearLayout leftButtonsLayout = (LinearLayout) findViewById(R.id.LeftButtonsLayout);
imageView = (ImageView) findViewById(R.id.ResetButton);
Log.d("DEBUG", CLASS_NAME + "scaleLeftButtonsLayoutContents: \n" +
"linear layout height: " + leftButtonsLayout.getHeight() + "\n" +
"text height: " + ((TextView)findViewById(R.id.Jump)).getHeight() + "\n" +
"image height: " + imageView.getLayoutParams().height);
}
1) If I place the setContentVew() call after the Log.d() debug print, I get a Null Pointer Exception. Why? Is memory not allocated for the LinearLayout before it's used on the view?
2) The prints I see are:
linear layout height: 0
text height: 0
image height: -2
What am I doing wrong here? I expected to see sane values here, since I can see the imageView on the device screen.
3) I was planning to scale the image using:
imageView.getLayoutParams().height = newHeight. Is that right to do? Will doing this automatically update the imageView on the screen, or will I have to do a setContentView() again?
Thanks in advance for your help.
UPDATE
Thanks for your answers everyone. I've overridden the onWindowFocusChanged() method of my activity, but when I check the size of the nested ImageView below, it's reported as -2. Resizing it works, but I'm curious why it's -2 when it should've had a sane value. My code's as follows:
#Override
public void onWindowFocusChanged (boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus)
scaleLeftButtonsLayoutContents();
}
private void scaleLeftButtonsLayoutContents () {
LinearLayout leftButtonsLayout = (LinearLayout)findViewById(R.id.LeftButtonsLayout);
imageView = (ImageView) findViewById(R.id.JumpButton);
Log.d("TAG", CLASS_NAME + "JumpButton.height " + imageView.getLayoutParams().height);
imageView.getLayoutParams().height = verticalSpaceAvailable;
imageView.getLayoutParams().width = verticalSpaceAvailable;
leftButtonsLayout.requestLayout();
}
This produces the print:
JumpButton.height -2
The resize produces a sane image, but why is the initial height -2?
To answer your points,
1) It is because you haven't initailaized your Button or ImageView. Since you call your Log before doing this, obviously the Button and ImageView are null and hence you get the exception.
2)And initializing doesn't mean that your view are completely drawn to provide you with width and height. So you have to provide the time to get itself drawn. But unfortuanately we don't know the exact time it takes to get drawn. So Android provides this method,
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
// which gets called when your view is drawn.
}
Just now answered a similar question here.
So what you have to do is, add your Log inside this method in your Activity and then check the resulting width and height.
3) To answer your third question, you definitely should not call setContentView() once again, which might throw you some other exception. But when considering scaling you might make use of some bitmaps to do this.
Here are some answers for you:
1) If you place the setContentView after calling view.getHeight() you will get null pointer because that view is not set on the Activity content therefore you can't get a reference to it before setting it to the content of the Activity
2) You see that because the view doesn't had time to layout.. if you want to see the height/width of a view it's better to use a ViewTreeObserver listener like this:
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
/* don't forget to remove the listener after you use it once */
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
Log.d("MY VIEW WIDTH","width:"+view.getWidth());
}
});
3) After you set the layout params of a view don't forget to call view.requestLayout() to make sure that your view will refresh. You don't have to call setContentView() again.
EDIT: Also the width of your LinearLayout has to be at least wrap_content if not fill_parent or a value greater than 0 if you want to see the child views of the Linear Layout..
You cannot do like this. Because the linearlayout is the main container of your activity. You cannot provide android:layout_weight="10" and android:layout_width="0dip" to the main layout. create one Linear layout outside this android:id="#+id/LeftButtonsLayout" and give the layout height and width to fill_parent or match_parent. This will work in your case.
And one more thing, You cannot allow to call elements of layout before the setContentView.

android - add n number of views in scroll view

i am designing an app for android tablets. I have created a layout file which contains the application bar, next is some buttons. In the middle of the screen i want to have a horizontal scroll view inside which i need to show some images.
The number of images inside the scroll view depends upon the return data from the url. For this i am maintaining an array list. According to the size of the array i need to create the image views withing the scroll view.
I have placed all other buttons, textviews in the layout file and i need to make the above said view alone through coding, how to do this.
If the array size is 19, then the list of images within scroll view to be shown in the following order only
1 4 7 10 13 16 19
2 5 8 11 14 17
3 6 9 12 15 18
In iPad iBook apps library page, the books will be listed out in this way.
how to do this....
not sure but can try approach like this
1- Create/inflate a horizontal scrollview ..
2- make for loop running i= 0 to x
where x= (totalCount/3)+(totalCount%3>0?1:0)
3- Create a Linear layout with orientation vertical
4- create one more loop form j=0 to 3 or (i+1)*3+j< totalCount
5- add your element layout in Linear layout
6 after the inner loop closed add Linear layout in horizontal scroll-view
loop termination condition like the value of x may not be exact please check them
For making item clickable
1- take any view from element layout like in you case image-view is good option
2- creates a class in you activity or better to extend you activity with clickListner.
3- while creating the imageView for each element set this listener to all
4- Set the data object or index with element with image-view in tad using SetTag
5- in Onclick function you will get image-view as argument and use getTag to get that data of attached with clicked element
Thanks to Dheeresh Singh
Following is my main.xml file
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linear_1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
i have my Horizontal scroll view in my main.xml file
public class LayoutActivity extends Activity
//implements OnClickListener
{
ViewGroup layout;
LinearLayout lr;
int x;
int total = 4;
int count = 0;
LinearLayout lay;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
count = 0;
layout = (ViewGroup)findViewById(R.id.linear_1);
x = (total/3)+(total%3 > 0?1:0);;
for(int i = 0; i < x; i++)
{
lr = new LinearLayout(this);
lr.setOrientation(LinearLayout.VERTICAL);
layout.addView(lr);
for(int j = 0; j < 3; j++ )
{
count++;
final View child = getLayoutInflater().inflate(R.layout.inflateview, null);
lay = (LinearLayout)child.findViewById(R.id.threeByThree_tableRow1_1_Layout1);
lay.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "selected id is "+child.getId(), Toast.LENGTH_SHORT).show();
}
});
lr.addView(child);
child.setId(count);
if(i == total)
{
break;
}
}
}
}
}
in the above code i have lr is the LinearLayout to display it in vertical order and View child is the data which i need to show in both vertical and horizontal order.
Thanks a lot Dheeresh Singh

Adding a simple ScrollView to Gallery causes a memory leak

I've run into what I can only categorize as a memory leak for ScrollView elements when using the Gallery component.
A short background. I've got an existing app that is a photo slideshow app.
It uses the Gallery component, but each element in the adapter is displayed in full-screen.
(full source is available at this link)
The adapter View element consist of an ImageView, and two TextViews for title and description.
As the photos are of a quite high-resolution, the app uses quite a lot of memory but the Gallery has in general manage to recycle them well.
However, when I am now implementing a ScrollView for the description TextView, I almost immediately run into memory problems. This the only change I made
<ScrollView
android:id="#+id/description_scroller"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fillViewport="true">
<TextView
android:id="#+id/slideshow_description"
android:textSize="#dimen/description_font_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:layout_below="#id/slideshow_title"
android:singleLine="false"
android:maxLines="4"/>
</ScrollView>
I did a heap dump and could clearly see that it was the Scrollview which was the root of the memory problems.
Here are two screenshots from the heap dump analysis. Note that the ScrollView retains a reference to mParent which includes the large photo I use
PS same problem occurs if I use the TextView's scrolling (android:scrollbars = "vertical" and .setMovementMethod(new ScrollingMovementMethod());
PSS Tried switching off persistent drawing cache, but no different dreaandroid:persistentDrawingCache="none"
Have you tried removing the scroll view whenever it's container view scrolls off the screen? I'm not sure if that works for you but its worth a shot? Alternatively, try calling setScrollContainer(false) on the scroll view when it leaves the screen. That seems to remove the view from the mScrollContainers set.
Also, this question, answered by Dianne Hackborn (android engineer), explicitly states not to use scrollable views inside of a Gallery. Maybe this issue is why?
Just add this -> android:isScrollContainer="false"
<ScrollView
android:id="#+id/description_scroller"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fillViewport="true"
android:isScrollContainer="false">
There is some source why this is appear:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/view/View.java
the problem is:
setScrollContainer(boolean isScrollContainer)
by default:
boolean setScrollContainer = false;
but in some cases like this
if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
setScrollContainer(true);
}
it can be true, and when it happends
/**
* Change whether this view is one of the set of scrollable containers in
* its window. This will be used to determine whether the window can
* resize or must pan when a soft input area is open -- scrollable
* containers allow the window to use resize mode since the container
* will appropriately shrink.
*/
public void setScrollContainer(boolean isScrollContainer) {
if (isScrollContainer) {
if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
mAttachInfo.mScrollContainers.add(this);
mPrivateFlags |= SCROLL_CONTAINER_ADDED;
}
mPrivateFlags |= SCROLL_CONTAINER;
} else {
if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
mAttachInfo.mScrollContainers.remove(this);
}
mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
}
}
mAttachInfo.mScrollContainers.add(this) - all view put into ArrayList this lead to leak of memory sometimes
Yes i noticed the problem, sorry for my previous comment, i've tried to empty the Drawables
by setting previous Drawable.setCallBack(null); but didnt work, btw i have nearly the same project, i use ViewFlipper instead of Gallery, so i can control every thing, and i just use 2 Views in it, and switch between them, and no memory leak, and why not you resize the Image before displaying it, so it will reduce memory usage (search SO for resizing Image before reading it)
Try moving "android:layout_below="#id/slideshow_title" in TextView to ScrollView.
Ended up with implementing a workaround that uses a TextSwitcher that is automatically changed to the remaining substring every x seconds.
Here is the relevant xml definition from the layout
<TextSwitcher
android:id="#+id/slideshow_description"
android:textSize="#dimen/description_font_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/slideshow_description_anim1"
android:textSize="#dimen/description_font_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="2"
android:textColor="#color/white"
android:singleLine="false"/>
<TextView
android:id="#+id/slideshow_description_anim2"
android:textSize="#dimen/description_font_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="2"
android:textColor="#color/white"
android:singleLine="false"/>
</TextSwitcher>
Here I add the transition animation to the TextSwitcher (in the adapter's getView method)
final TextSwitcher slideshowDescription = (TextSwitcher)slideshowView.findViewById(R.id.slideshow_description);
Animation outAnim = AnimationUtils.loadAnimation(context,
R.anim.slide_out_down);
Animation inAnim = AnimationUtils.loadAnimation(context,
R.anim.slide_in_up);
slideshowDescription.setInAnimation(inAnim);
slideshowDescription.setOutAnimation(outAnim);
Here is how I swap to the part of the description
private void updateScrollingDescription(SlideshowPhoto currentSlideshowPhoto, TextSwitcher switcherDescription){
String description = currentSlideshowPhoto.getDescription();
TextView descriptionView = ((TextView)switcherDescription.getCurrentView());
//note currentDescription may contain more text that is shown (but is always a substring
String currentDescription = descriptionView.getText().toString();
if(currentDescription == null || description==null){
return;
}
int indexEndCurrentDescription= descriptionView.getLayout().getLineEnd(1);
//if we are not displaying all characters, let swap to the not displayed substring
if(indexEndCurrentDescription>0 && indexEndCurrentDescription<currentDescription.length()){
String newDescription = currentDescription.substring(indexEndCurrentDescription);
switcherDescription.setText(newDescription);
}else if(indexEndCurrentDescription>=currentDescription.length() && indexEndCurrentDescription<description.length()){
//if we are displaying the last of the text, but the text has multiple sections. Display the first one again
switcherDescription.setText(description);
}else {
//do nothing (ie. leave the text)
}
}
And finally, here is where I setup the Timer which causes it to update every 3.5 seconds
public void setUpScrollingOfDescription(){
final CustomGallery gallery = (CustomGallery) findViewById(R.id.gallery);
//use the same timer. Cancel if running
if(timerDescriptionScrolling!=null){
timerDescriptionScrolling.cancel();
}
timerDescriptionScrolling = new Timer("TextScrolling");
final Activity activity = this;
long msBetweenSwaps=3500;
//schedule this to
timerDescriptionScrolling.scheduleAtFixedRate(
new TimerTask() {
int i=0;
public void run() {
activity.runOnUiThread(new Runnable() {
public void run() {
SlideshowPhoto currentSlideshowPhoto = (SlideshowPhoto)imageAdapter.getItem(gallery.getSelectedItemPosition());
View currentRootView = gallery.getSelectedView();
TextSwitcher switcherDescription = (TextSwitcher)currentRootView.findViewById(R.id.slideshow_description);
updateScrollingDescription(currentSlideshowPhoto,switcherDescription);
//this is the max times we will swap (to make sure we don't create an infinite timer by mistake
if(i>30){
timerDescriptionScrolling.cancel();
}
i++;
}
});
}
}, msBetweenSwaps, msBetweenSwaps);
}
Finally I can put this problem to a rest :)

Categories

Resources