Friday, June 03, 2011

Listview For dynamic

This is the code for creating listview Dynamically In android.first create one class name it as"Listview for dynamic.java" 

listviewfourdynamic.java:-

package com.listviews;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;


public class ListViewFourDynamic extends ListActivity implements OnKeyListener {

    String text;
    private EditText mUserText;
   
    private ArrayAdapter<String> mAdapter;
    private ArrayList<String> mStrings = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.dynamiclist);
       
        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings);
       
        setListAdapter(mAdapter);
       
        mUserText = (EditText) findViewById(R.id.enterText);

       
        mUserText.setOnKeyListener(this);
    }


    private void sendText() {
         text = mUserText.getText().toString();
      
        mAdapter.add(text);
       
        mUserText.setText(null);
    }
 
    public boolean onKey(View v, int keyCode, KeyEvent event) {
       
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
           
            switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                   sendText();
                    return true;
            }
        }
        return false;
    }
}

And this Is the XML file

Dynamiclist.xml:-

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingLeft="8dip"
    android:paddingRight="8dip">
   
    <ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:stackFromBottom="false"
        android:transcriptMode="normal"/>
       
    <EditText android:id="@+id/enterText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
       
</LinearLayout>

 this is the way to create a list view dynamically

No comments:

Post a Comment