In this tutorial we will explain how to create ListView programmatically and how to used swicth case in ListView onItemClick() in android. explain testcode below;
package com.example.androidbeginnerpoint;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
String[] planets = new String[] { "Apple", "Banana", "Mango", "Grapes","Orange"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create listview programmatic
final ListView list = new ListView(this);
//set a ArrayAdapter in listview and bind the string array
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, planets);
list.setAdapter(adapter);
//set click event on listview index possition
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
//used the switch case
switch (position) {
case 0:
Toast.makeText(getApplication(),position+"\n"
+list.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(getApplication(),position+"\n"
+list.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(getApplication(),position+"\n"
+list.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
break;
case 3:
Toast.makeText(getApplication(),position+"\n"
+list.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
0 comments