Playing with Lists in Android - Part I

In this tutorial, first I am going to show you a simple but useful tutorial on ListView in Android.

Whatever we are entering in the editText will be shown in the list, like a starting for chat application UI.

Things required for this are ListView, adapter, arrayList, editText and a button. I created the layout in XML, as this is a small UI with few components. Another reason for this is, for my few previous projects, I need to use java for creating layouts.

The complete code will look like this..



public class SampleListView_Chat extends Activity {

ListView lView;
ArrayList list;
EditText eText;
Button but;
ArrayAdapter adapter;
LinearLayout layout, subLayout;
LayoutParams params, lParams;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
subLayout = new LinearLayout(this);
params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
eText = new EditText(this);
but = new Button(this);
lView = new ListView(this);
list = new ArrayList();
but.setText("Send");
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
but.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
list.add(eText.getText().toString());
eText.setText(null);
lView.setAdapter(adapter);
}
});
lParams.height = 380;
layout.addView(lView, lParams);
eText.setWidth(260);
subLayout.addView(eText, params);
subLayout.addView(but, params);
layout.addView(subLayout, params);
setContentView(layout);
}
}



Another thing that is very useful in chat applicationa and for other purposes is to see the last entry that we entered. For scrolling the listview, in XML



android:transcriptMode="alwaysScroll"



In java, the code is,


listView.setStackFromBottom(true);
listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);




Comments

Popular posts from this blog

AlarmManager and Notification in Android

Swipe Action and ViewFlipper in Android

Difference between SurfaceView and View in Android