开发者

How do I add elements dynamically to a view created with XML

开发者 https://www.devze.com 2023-03-13 04:21 出处:网络
I\'m trying to add dynamic content to a view that has been created with XML. I have a view \"profile_list\" that has a ScrollView that I like to add some elements to.

I'm trying to add dynamic content to a view that has been created with XML.

I have a view "profile_list" that has a ScrollView that I like to add some elements to.

Here is some code of what I'm trying to do.

// Find the ScrollView 
ScrollView sv = (ScrollView) this.findViewById(R.id.scrollView1);

// Create a LinearLayout element
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

// Add text
tv = new TextView(this);
tv.setText("my text");
ll.addView(tv);

// Add the LinearLayout element to the ScrollView
sv.addView(ll);

// Display the view
setContentView(R.layout.profile_list);

The plan is to add a TableLayout and fill it dynamically and not just a dummy text but first I must get this to work.

Any help is welcome.

Kind Regards Olle

I found the solution!

Stupid me I had left a element in my ScrollView in my XML-file!

Anyway her is a working example:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.profile_list, null);

    // Find the ScrollView 
    ScrollView sv = (ScrollView) v.findViewById(R.id.scrollView1);

    // Create a LinearLayout element
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);

    // Add text
    TextView tv = new TextView(this);
    tv.setText("my text");
    ll.addView(tv);

    // Add the LinearLayout element to the ScrollView
    sv.addView(ll);

    // Display the view
    setContentView(v);

And the XML-file to match

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ScrollView 
        android:id="@+id/scrollView1" 
        android:clickable="true" 
        android:layout_weight="1" 
        android:layout_w开发者_C百科idth="fill_parent" 
        android:layout_marginBottom="50px" 
        android:layout_height="fill_parent">
    </ScrollView>

</LinearLayout>

Hope this will help someone. Thanks for all help!


The way that you are adding things to the view is basically right - you just get the container object by its ID and then add them.

It looks like you are setting the content view to be the wrong view though. You should inflate the view, add the children and set it as the content view, or set the content view from a resource ID then do the manipulation. What you are doing is manipulating a view and then adding a different one. Try moving your setContentView(...) to the start of the block.

0

精彩评论

暂无评论...
验证码 换一张
取 消