Search code examples
androidandroid-intenthorizontalscrollview

Insert a view dynamically in a HorizontalScrollView in Android


I'm developing an application for Android tablet 3.0 that has one activity that should be scrollable in the horizontal axis, like an e-book.

For that, I'm using a RelativeLayout inside a HorizontalScrollView on my layout. Here is the XML:

<?xml version="1.0" encoding="utf-8"?>

    <HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="800px"
    android:id="@+id/horizontalScroll"
    android:background="#C6D7D2" android:layout_height="600px">

    <RelativeLayout android:id="@+id/container" android:layout_width="fill_parent" android:layout_height="fill_parent">        
    </RelativeLayout>


</HorizontalScrollView>

This xml file is called main.xml.

What I'm doing in the java file is:

setContentView(R.layout.main);
parent = (ViewGroup) findViewById(R.id.container);
View v = createView(); // Thats working for sure.
parent.addView(v);

But it is not working, the view V doesn't show on the screen. But if i do

addContentView(v)

it adds the view v to the screen (the proof that my method works), but it isn't scrollable since it is outside the HorizontalScrollView. What am I doing wrong?

UPDATE: I tried with that and it also didn't work out:

setContentView(R.layout.main);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ViewGroup parent = (ViewGroup) findViewById(R.id.container);
View v = new View(this);
v.setBackgroundColor(Color.BLUE);
parent.addView(v,params);

I don't get a blue background.


Solution

  • Change the width of Relativelayout to wrap_content.

    Try using this method to add the view.

    void addView (View child, ViewGroup.LayoutParams params)
    

    EDIT:
    Remove android:orientation="horizontal" from the HorizontalScrollView