Search code examples
androidandroid-listviewandroid-scrollview

android listview or scrollview: for a form with dynamic number of fields


Let's say I need to take names of movies the person likes. I don't know how many he likes so I want to present him with just one text field. He can click a button and add more fields to fill. I can use ScrollView of course but should I think about using a ListView? If so, I can't seem to understand how. Please help


Solution

  • try this:

      public class TestingActivity extends ListActivity {
    /** Called when the activity is first created. */
    
    EditText value;
        Button insert;
    
        ArrayList<String> data=new ArrayList<String>();
        /** Called when the activity is first created. */
    
        @SuppressWarnings("unchecked")
        @Override
    
        public void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.main);
    
    
    
              insert = (Button) findViewById(R.id.button2);
              value=(EditText)findViewById(R.id.value);
              insert.setOnClickListener(new OnClickListener() {
    
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    data.add(value.getText().toString());
                    getListView().setAdapter(new  ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, data));
    
                        }
            });
              getListView().setAdapter(new  ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, data));
    
        }
    
            }
    

    xml is:

      <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
    
    
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
    
            <EditText
                android:id="@+id/value"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1" />
    
            <Button
                android:id="@+id/button2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="insert" />
        </LinearLayout>
    
        <ListView
            android:id="@android:id/list"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scrollingCache="false" >
        </ListView>
    
    </LinearLayout>