Iam trying to create a list view dynamically, Please provide me an example for list view in android...
Activity class......
public class UsersListActivity extends ListActivity{
RegisterUser registerUser;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] statesList = getListOfAllUsers();
Toast.makeText(getApplicationContext(),
"States Array lentgh is : " + statesList.length,
Toast.LENGTH_LONG).show();
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
statesList));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"You selected : "+((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}}
and create an xml file named list_item.xml and paste the below code.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" android:textColor="#ffffff" android:textStyle="bold" android:background="#drawable/border_cell">
</TextView>
You can create your own List View by extending Base adapter class
public class ListAdapterDroidman extends BaseAdapter{
private ArrayList<ListitemDroidman> list = new ArrayList<ListitemDroidman>();
#SuppressWarnings("unused")
private Context context;
public ListAdapterDroidman(Context context) {
this.context = context;
}
public void addItem(ListitemDroidman item) {
list.add(item);
}
public void addItem(ListitemDroidman item,int pos)
{
list.add(pos, item);
}
public void removeItem(int pos)
{
list.remove(pos);
}
public void clearList()
{
list.clear();
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return list.get(position);
}
}
Then create your own layout
public class ListitemDroidman extends LinearLayout {
TextView filename;
ImageView iv;
public ListitemDroidman(Context context) {
super(context);
}
public void setInfo(Context context, Bitmap icon, String fname,int colorId) {
iv=new ImageView(context);
iv.setImageBitmap(icon);
iv.setPadding(0, 0, 20, 0);
addView(iv);
filename = new TextView(context);
filename.setTextSize(20);
filename.setTextColor(getResources().getColor(colorId));
filename.setText(fname);
addView(filename);
}
}
Now create listitems in your activityClass
create object of the adapter that u have created
myListitem = new ListitemDroidman(this);
icon = BitmapFactory.decodeResource(getResources(),
R.drawable.folder_icon);
myListitem.setInfo(getApplicationContext(), icon, filelist[i],
R.color.color_white);
add the listitem to the adaper as in normal list
la_file.addItem(myListitem);
Try this tutorial to understand how to use ListView.
http://developer.android.com/resources/tutorials/views/hello-listview.html
Why don't you just take a look at the ApiDemos of your android SDK..
You can find 14 examples of ListActivities implementations..
Or just search here or on Google, you can find lots of examples
Then if you want to achieve something in particular you can ask a more specific question here, does it sound fair?
Related
My Activity which displays the GridView crashes whenever I try to open the said Activity. I'm kind of clueless as to what's wrong with my codes, please help me regarding this.
public class AppContainerActivity extends Activity {
private PackageManager manager;
public List<AppDetails> apps;
GridView AppDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_container);
AppDrawer = (GridView) findViewById(R.id.AppDrawer);
AppDrawer.setAdapter(new ItemAdapter(this, apps));
}
//Fetch installed apps on device
public void loadApps(){
manager = getPackageManager();
apps = new ArrayList<AppDetails>();
Intent getApp = new Intent(Intent.ACTION_MAIN,null);
getApp.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> availableActivities = manager.queryIntentActivities(getApp, 0);
for(ResolveInfo ri : availableActivities){
AppDetails app = new AppDetails();
app.appIcon = ri.activityInfo.loadIcon(manager);
apps.add(app);
}
}
}
ItemAdapter:
class ItemAdapter extends BaseAdapter {
Context mContext;
Integer[] icon;
ItemAdapter(Context c, List<AppDetails> apps){
mContext = c;
icon = apps.toArray(new Integer[apps.size()]);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return icon.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView appIcon;
if(convertView == null) {
appIcon = new ImageView(mContext);
appIcon.setLayoutParams(new GridView.LayoutParams(85, 85));
appIcon.setScaleType(ImageView.ScaleType.CENTER_CROP);
appIcon.setPadding(8, 8, 8, 8);
} else {
appIcon = (ImageView) convertView;
}
appIcon.setImageResource(icon[position]);
return appIcon;
}
}
AppDetails:
class AppDetails {
Drawable appIcon;
}
XML layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<GridView
android:id="#+id/AppDrawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="70dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:scrollbars="horizontal"
android:stretchMode="spacingWidthUniform"
/>
</LinearLayout>
You passed an uninitialized Arraylist into the adapter, so it's null and throwing an error in the constructor when you get the size of the list
You should call the loadApps method before you set the adapter. Or make that return the arraylist, and pass that method to the adapter.
Additionally worth mentioning, you can extend an ArrayAdapter<AppDetails>instead of a BaseAdapter, or you should complete the implementation of the BaseAdapter with the getItem method not returning null. In case you do later want to access elements of the adapter.
You also could keep the arraylist in the adapter. No need to convert to an array
Is there any way to remove selected item from gridview.
I want to delete the selected item from my gridview.
I did not find any thing . my code is
public class ImageAdapter extends BaseAdapter{
Context context;
public ImageAdapter(Context context)
{
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 5, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
public Integer[] mThumbIds = {
R.drawable.sample_1,R.drawable.sample_2,R.drawable.sample_3,
R.drawable.sample_3,R.drawable.sample_1,R.drawable.sample_2,
R.drawable.sample_2,R.drawable.sample_3,R.drawable.sample_1
};
}
//////////////////
public class ImageActivity extends Activity {
ImageAdapter iAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
iAdapter = new ImageAdapter(this);
final GridView gView = (GridView)findViewById(R.id.grid_view);
gView.setAdapter(iAdapter);
gView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//gView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// gView.setItemChecked(position, true);
Toast.makeText(ImageActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
iAdapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_image, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.menu_delete)
{
Toast.makeText(this, "Delete",Toast.LENGTH_SHORT ).show();
}
return super.onOptionsItemSelected(item);
}
}
can anyone have idea .
thank
you are using a table :
public Integer[] mThumbIds = {
R.drawable.sample_1,R.drawable.sample_2,R.drawable.sample_3,
R.drawable.sample_3,R.drawable.sample_1,R.drawable.sample_2,
R.drawable.sample_2,R.drawable.sample_3,R.drawable.sample_1}
Tables are not modifiable.
Replace it by a List on which you will be able to make add or remove operations. Simply call notifyDataSetChanged when a change is made to let the adapter know that its list has been modified.
As Teovald and pskink suggested, you cannot have a fixed list of images and then implement the remove functionality that you are looking for. If you want to add remove, change your design and make sure your data set is also removable. What you have tried so far seems to be using some really basic code which is good to show basic GridView feature.
Just try this. Create a image data set class which returns the actual images. Store the images in a List that can be modified. Add setters/getters to this data set and also add a method to delete a particular item. Change your image adapter to use the image from this new data set. Whenever an image is deleted, call the notifyDataSetChanged on the adpater.
Good luck
I am writing an android app, and I am having trouble getting a row's position in ListView with CheckBox.
Here is a screenshot on the emulator:
I already made the ListView with CheckBoxes. But I can't figure out how find the row's position for each checked entry. And once I get the checked positions, I want to implement a Remove Selected action.
Please help!
Here is my code:
public class ListTest extends ListActivity implements OnCheckedChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//--- Importing StringsArray---
Bundle gotBasketScanner = getIntent().getExtras();
String[] StringArrayHistory = gotBasketScanner.getStringArray("fromHistory");
// ---Make Adapter---
setListAdapter( new ArrayAdapter<String>(ListTest.this,
android.R.layout.simple_list_item_multiple_choice,
StringArrayHistory));
// ---Put Array into a ListView and add Checkboxes to Listview
ListView list = getListView();
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
}
hey check this it will help you...
http://windrealm.org/tutorials/android/listview-with-checkboxes-without-listactivity.php
Android ListView with Checkbox and all clickable
http://appfulcrum.com/2010/09/12/listview-example-3-simple-multiple-selection-checkboxes/
Use onItemClick() in instead of onCheckedChangeListener...
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(getApplicationContext(), "Item "+position+" is clicked",
Toast.LENGTH_SHORT).show();
}
}
This is the better way to get the clicked position and id.
I hope this will solve your problem.
EDIT
I have updated the following line:-
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
now try ur code.
You can use PrefrenceScreen with CheckBoxPreference for easier and scalellable implementation
You can use CheckedTextView to implement the same:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:checkMark="?android:attr/listChoiceIndicatorMultiple">
</CheckedTextView>
addlist.xml
<?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" >
<ListView
android:id="#+id/mainListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</ListView>
<Button android:id="#+id/click"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click"/>
</LinearLayout>
And here is the activity GetCheckedTextPositionActivity. On click of the button you will get the positions of the listitem checked :
public class GetCheckedTextPositionActivity extends Activity {
private ListView myList;
private EfficientAdapter myAdapter;
private ArrayList<String> data;
private LayoutInflater mInflater;
private Button click;
private ArrayList<Integer> positions;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addlist);
positions = new ArrayList<Integer>();
data = new ArrayList<String>();
data.add("Bangalore");
data.add("Delhi");
data.add("Patna");
data.add("Mumbai");
click = (Button)findViewById(R.id.click);
mInflater = LayoutInflater.from(getApplicationContext());
myList = (ListView) findViewById(R.id.mainListView);
myAdapter = new EfficientAdapter(data, getApplicationContext());
myList.setAdapter(myAdapter);
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(positions.size() != 0){
for(Integer pos : positions){
Log.e("Positions checked :"," Positions :"+pos);
}
}
}
});
}
public class EfficientAdapter extends BaseAdapter {
private ArrayList<String> myData;
public EfficientAdapter(ArrayList<String> mData, Context ctx) {
// TODO Auto-generated constructor stub
this.myData = mData;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return myData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return myData.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int currentPos = position;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.main, null);
}
((CheckedTextView) convertView).setText(myData.get(position));
((CheckedTextView) convertView).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((CheckedTextView) v).toggle();
if(((CheckedTextView) v).isChecked()){
positions.add(currentPos);
}
}
});
return convertView;
}
}
}
Hope this helps.
I want to design each list item in the ListView can be clickable, and triger out which list item be clicked. But it can not. I tried the two methods: setOnItemClickListener() and setOnItemSelectedListener() on my code. I have had googled couple of references about the article, however it still can not work(clickable).
I would like post the code below: The code can display the list items and I can see the Log.d content for the line of Log.d(" mListView01.getCount()="," "+vc); on LogCat well. But, there is no any response if I clicked on the list Item.
if you don't mind, could you help point me out where I was wrong, thanks !
Code for creating the listView using the Activity Widget:
......
setContentView(R.layout.main_open);
TextView itemText = (TextView) findViewById(R.id.itemText);
TextView codeText = (TextView) findViewById(R.id.codeText);
itemText.setText(selectedItem);
codeText.setText(selectedCode);
ListView mListView01 = (ListView)findViewById(R.id.main_open_listview1);
String[] keys = new String[] {"title","title_image", "content",
"title1","title1_image","content1","title2","title2_image","content2"};
int[] resValues = new int[] { R.id.title, R.id.title_image, R.id.content,
R.id.title1, R.id.title1_image, R.id.content1,R.id.title2, R.id.title2_image, R.id.content2};
openDocAdapter opendoc = new openDocAdapter(this,localdcoumentlist, R.layout.main_open_content, keys, resValues );
mListView01.setSelected(true);
mListView01.setClickable(true);
mListView01.setAdapter(opendoc);
int vc = mListView01.getCount();
Log.d(" mListView01.getCount()="," "+vc);
mListView01.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Log.d("Selected From setOnItemSelectedListener, arg2=", " "+ arg2);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
mListView01.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
selectedViewPos = arg2;
Log.d("TitlesSelectionDialog(),selectedViewPos= "," "+ selectedViewPos);
Toast.makeText(getApplicationContext(), "selectedViewPos= "+ selectedViewPos, Toast.LENGTH_LONG).show();
}
});
......
Code for openDocAdapter:
private class openDocAdapter extends SimpleAdapter
{
private Context _con;
private List _List;
private int _listviewId;
private String[] _keys;
private int[] _resValues;
public openDocAdapter(Context context, ArrayList<HashMap<String,Object>> List , int listviewId, String[] keys, int[] resValues )
{
super(context, List, listviewId, keys, resValues);
_con =context;
_List = List;
_listviewId = listviewId;
_keys = keys;
_resValues = resValues;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.main_open_content, null);
}
TextView title = (TextView) v.findViewById(R.id.title);
(...Similiar codes define textView, imageViewsd.)
return v;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return super.getCount();
}
#Override
public Object getItem(int position)
{
// TODO Auto-generated method stub
return super.getItem(position);
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return super.getItemId(position);
}
}
Edit1: I found an article here About the Focus setting on the layout will cause clickable work or not work. So, I remove the lines of (I don't while it be coded here) in the xml file of layout. Then the setOnItemSelectedListener() method is worked while scrolling the list list with orange focus change. But it still not meet my expection.
Provlem Solved ! After couple hous googling/search and try_eror. And I would like share it if you are interesting.
The main cause of the problem is: I used the ScrollView as the basic layout for the row.xml(containing the content for each listview row). Then, I used the LinearLayout(Vertial) instead of it. The setOnItemClickedListener() method works fine now. I do not have any idea regarding this that will cause the ListView to be not clickable. If somebody know it, please tell us,
Below you can see the code, i implemented a simple adapter for my listview. But i can not get in to onListItemClick. can anyone has suggestions ?
actually it displays the list normally but i am not able to get onitemclick events . thanks in advance.
public class MyListActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<Frame> results = WebOperations
.loadList_Frame();
myAdapter = new MyListAdapter(MyListActivity.this);
myAdapter.internalList = results;
setListAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
};
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " please show toast!!!!!!!!!", Toast.LENGTH_LONG).show();
}
public static class MyListAdapter extends BaseAdapter {
public ArrayList<Frame> internalList;
public LayoutInflater mInflater;
public int pageCount = 0;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
if (internalList == null)
return 0;
return internalList.size();
}
public Object getItem(int position) {
if (internalList == null || internalList.size() < position)
return null;
return internalList.get(position);
}
public long getItemId(int position) {
if (internalList == null || internalList.size() < position)
return 0;
return internalList.get(position).getId();
}
public View getView(int position, View arg1, ViewGroup parent) {
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.entryrow, null);
try {
String gunlukText = String.format(" %s ",
internalList.get(position).getKeyText().toString());
TextView entry = (TextView) v
.findViewById(R.id.textViewEntryText);
entry.setText((CharSequence) gunlukText);
} catch (Exception e) {
Log.d("aaaaaaaaaaaaaaaaaaa", "errorrrrrrrrrrr");
}
}
return v;
}
}
}
EDIT 1 : I am adding entry_row layout xml file below.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewEntryText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:padding="5dp"
android:paddingLeft="10dp"
android:text="#string/Ana_Sayfa"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
You should consider adding your listener to your listview :
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " please show toast!!!!!!!!!", Toast.LENGTH_LONG).show();
}
});
add onclicklistener into getView method just before return view.
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.w("position", position + "");
}
});
check if it helps..
Didi you try, on your layout/entryrow, to add the addStatesFromChildrenattribute and set it to true ?
http://developer.android.com/reference/android/view/ViewGroup.html#attr_android:addStatesFromChildren
Please refer one of the good example given in API demo of custom BaseAdapter from http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List13.html Just override onListItemCLicked and check. It works perfectly fine. Try to modify your code accordingly.