start new activity on click listview item - android

I need some help to do a simple click in a listview item to open a new Activity. I have seen a lot of this kinda issues here but no one helped me.
public class CustomListView extends ListActivity {
private EfficientAdapter adap;
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
adap = new EfficientAdapter(this);
setListAdapter(adap);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
startActivity(new Intent(CustomListView.this, next.class));
}
public static class EfficientAdapter extends BaseAdapter implements Filterable {
private LayoutInflater mInflater;
private Bitmap mIcon1;
private Context context;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.adaptor_content, null);
convertView.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {
}
});
convertView.setTag(holder);
}else{
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
...
}
}
I tried also adding the next code inside of onCreate method from CustomListView class but it doesn't work either
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startActivity(new Intent(CustomListView.this, next.class));
}
});

Remove the onListItemClick() from your CustomListView class and place the startActivity() method inside the convertView.setOnClickListener().
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), two.class));
}
});

Try this code. I am sure It is gonna help you and dont set class to an xml file like this;
setContentView(R.layout.second);
make sure that you did put that code above in your class, else you are gonna get an error while openin a new activity.
package com.exampled.list;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String [] names ={
"Iphone",
"Samsung",
"Nokia",
"Ericsson",
"BlackBerry",
"Benq"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,names));
}
public void onListItemClick(ListView Parent, View v, int position,long id){
startActivity(new Intent(MainActivity.this, Second.class));
//Toast.makeText(this, "Clicked on : " + names[position], Toast.LENGTH_LONG).show();
}
#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;
}
}

In you code one.this refers to the Context.
Since your Activity's name is CustomListView, you should write CustomListView.this instead of one.this.
You could also use getApplicationContext().

Try putting the startActivity(new Intent(one.this, two.class));-code into
convertView.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {...}
});
What does one.this refer to? It should be a Context

Related

Changing the default listViews item clicked to StringBuffer instead (displays popup by default)

I have a ListView that displays a list of items and I want to display further more details when any item is clicked using StringBuffer. But I'm having an issue because android default setOnItemClickListener bypasses the StringBuffer view that I'm defining inside the click event, and just displays the the item view in a popup.
Here is my code and I will include some screen shots in order to clarify my point a bit more
import android.app.AlertDialog;
import android.app.Fragment;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
public class SummerJobsFragmnet extends Fragment {
public SummerJobsFragmnet() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static Fragment getInstance() {
Fragment fragment = new SummerJobsFragmnet();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void showMessage (String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final MainActivity activity = (MainActivity) getActivity();
String [] places = activity.getAllPositionsNamesPhone().toArray(
new String[activity.getAllPositionsNamesPhone().size()]);
final ListView list = (ListView) getView().findViewById(R.id.joblistView);
int prgmImages=R.mipmap.ic_launcher;
list.setAdapter(new CustomListAdapter(activity,places,prgmImages));
// OnClick listner for the individual cells of the listView
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the IDs of each column in the database
String [] IDs = activity.getAllColumnsIDs().toArray(
new String[activity.getAllColumnsIDs().size()]);
// loop throught the IDs and see if they match the listView
// item ids. if yes, display the detail
DataBaseHelper summerJobDB;
summerJobDB = new DataBaseHelper(activity);
for (int i = 0; i >= IDs.length; i++) {
if (i == id) {
Cursor res = summerJobDB.getAllData();
if (res.getCount() ==0){
// show some message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
// append the values from the database to the buffer.
// this is based on the index number of the columns
while (res.moveToNext()) {
buffer.append(res.getString(1)+ "/" + res.getString(2) +"\n");
buffer.append("Starts on " + res.getString(3)+"\n\n");
buffer.append("Address: \n"+ res.getString(5)+"\n\n");
buffer.append("Phone: \n"+ res.getString(6)+"\n\n");
buffer.append("Hours: \n"+ res.getString(4)+"\n\n");
}
// show all data here
showMessage("Data",buffer.toString());
}
}
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.displayjobs, container, false);
}
}
and here is the CustomListAdapter.java
import android.widget.BaseAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class CustomListAdapter extends BaseAdapter {
String [] result;
Context context;
int imageId;
private static LayoutInflater inflater=null;
public CustomListAdapter(MainActivity mainActivity, String[] places, int prgmImages) {
// TODO Auto-generated constructor stub
result=places;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.display_job_cell_view, null);
holder.tv=(TextView) rowView.findViewById(R.id.Itemname);
holder.img=(ImageView) rowView.findViewById(R.id.icon);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId);
/*
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
*/
return rowView;
}
}
first image
Here is what I get
here is the logcat error after making the modifications
You have defined onClickListener on your list-items (rowView.setOnClickListener) - this is what gets called instead of the listView's setOnItemClickListener. You need to remove (comment out) this in the CustomListAdapter class:
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
You need to also call listView.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); so that only the listView's item click listener can be invoked even if the row item of list are set as focusable or clickable.
Then the dialog should show as you'd expect. Please try this and let us know if it works or what errors you get.

is it possible to edit field from listview on long click action?

Is it possible to have such functionality in android? When user longclicks row in a list popup window opens with option to edit content?
Yes it is. First of all you need to create your own Dialog with appropriate xml:
private static class EditListItemDialog extends Dialog implements View.OnClickListener {
private EditText editText;
public EditListItemDialog(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
Button btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
}
#Override
public void onClick(View v) {
editText.getText().toString();//here is your updated(or not updated) text
dismiss();
}
}
Then add listener at setOnLongClickListener:
ListView listView = new ListView(this);
listView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
new EditListItemDialog(v.getContext()).show();
return true;
}
});
Finally you need to update data in your ListView. The right way is to update Adapter of your list view which finally will update ListView.
Ok, I managed to make Dialog file as in your example:
package com.example.classorganizer;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
class EditListItemDialog extends Dialog implements View.OnClickListener {
private View editText;
public EditListItemDialog(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
}
#Override
public void onClick(View v) {
((TextView) editText).getText().toString();//here is your updated(or not updated) text
dismiss();
}
}
I created an xml file for Dialog file:
<?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:orientation="vertical" >
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
Then I updated my Display List file with this code:
ListView listView = new ListView(Monday.this);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(view.getContext()).show();
return true;
}
});
And here is full file that displays list of rows to be edited upon Long Click:
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.cookbook.data.Constants;
import com.cookbook.data.MyDB;
public class Monday extends ListActivity {
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
private class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
//new code below
ListView listView = new ListView(Monday.this);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(view.getContext()).show();
return true;
}
}); //end of new code
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
There you can see where I put the new code. Unfortunately, upon long click row is not being updated. I mean, the dialog file seems that is not being launched. Is it because I put the code in the wrong place or am I missing something else?

AlertDialog with ListView on BaseAdapter

I am getting the teams from an arraylist and show on a listview with their logos. It is working without problem. But I want to remove an item when I click long on a listview item with an yes - no alert dialog. Here is my codes and custom adapter.
package com.mesutemre.takimlarlistview;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class TakimBaseAdapter extends BaseAdapter {
Context context;
private LayoutInflater inflater = null;
private TextView lblAd, lblAciklama;
private ImageView imgTakim;
private ArrayList<Takim> items;
public TakimBaseAdapter(Context context, ArrayList<Takim> items) {
this.context = context;
this.items = items;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.activity_main, null);
lblAd = (TextView) vi.findViewById(R.id.textView1);
lblAd.setTextColor(Color.BLUE);
lblAciklama = (TextView) vi.findViewById(R.id.textViewAciklama);
imgTakim = (ImageView) vi.findViewById(R.id.takimImage);
lblAd.setText(items.get(position).getTakim_ad());
lblAciklama.setText(items.get(position).getTakim_aciklama());
int logoID = context.getResources().getIdentifier(
items.get(position).getImage(), "drawable",
context.getPackageName());
imgTakim.setImageResource(logoID);
return vi;
}
}
And I put the items of ArrayList of teams in MainActivity and it is here;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*final ArrayAdapter<Takim> adapter = new TakimAdapter(this,
R.layout.activity_main, getTakimlar());*/
final BaseAdapter adapter = new TakimBaseAdapter(MainActivity.this, getTakimlar());
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long arg3) {
Takim stakim = (Takim) parent.getItemAtPosition(position);
Toast.makeText(getBaseContext(),
"Takım : " + stakim.getTakim_ad(), Toast.LENGTH_SHORT)
.show();
}
});
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long arg3) {
final Takim stakim = (Takim) parent.getItemAtPosition(position);
// burada AlertDialog.Builder'ın constructor'ına dikkat edin.
// Listactivitymizin context'ini atıyoruz.
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Bu takımı silmek istediğinizden emin misiniz?");
builder.setPositiveButton("Evet",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
getTakimlar().remove(which);
adapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("Hayır",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
adapter.notifyDataSetChanged();
}
});
builder.show();
return false;
}
});
}
#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;
}
// Takimlar ekleniyor
private ArrayList<Takim> getTakimlar() {
ArrayList<Takim> takimList = new ArrayList<Takim>();
takimList.add(new Takim("Galatasaray", "19", "galatasaray"));
takimList.add(new Takim("Fenerbahçe", "18", "fenerbahce"));
takimList.add(new Takim("Beşiktaş", "13", "bjk"));
takimList.add(new Takim("Trabzonspor", "6", "trabzon"));
takimList.add(new Takim("Bursaspor", "1", "bursaspor"));
return takimList;
}
}
I am getting ArrayOutofBound Exception because of getTakimlar().remove(which);. How can I remove an item from my ArrayList in this situation?
Try :
if (view == null || takimList.isEmpty()) {
} else {
takimList.remove(which);
adapter.notifyDataSetChanged();
}
Use takimList.remove(which);
instead of getTakimlar().remove(which);

Get text content in EditText ListView after click button issue

I have a Listview of EditText and I need to get the String values of each edited row when I click a confirm button, but I don't know how.
I have tried to adapt some sample with no success ( I get always the default values and not the edited values).
My attempt is this
public class MyActivity extends Activity {
static int nItems;
ImageButton confirmButton;
ListView myList;
ListViewAdapterEditText adapterG1, adapterG2, adapterG3;
#Override
public void onCreate(Bundle savedInstanceState) {
.....
myList = (ListView) findViewById(R.id.listaG1);
myList.setItemsCanFocus(true);
adapterG1 = new ListViewAdapterEditText();
myList.setAdapter(adapterG1);
}
OnClickListener mConfirmButtonListener = new OnClickListener() {
public void onClick(View v) {
ArrayList a1 = adapterG1.getItems();
for (int i = 0; i < nItems; i++) {
System.out.println(a1.get(i)
+ "\n\n");
}
};
public class ListViewAdapterEditText extends BaseAdapter {
private LayoutInflater mInflater;
public ArrayList myItems = new ArrayList();
ListItem listItem;
public ListViewAdapterEditText() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < nItems; i++) {
listItem = new ListItem();
listItem.caption = "Caption" + i;
myItems.add(listItem);
}
notifyDataSetChanged();
}
public int getCount() {
return myItems.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public ArrayList<String> getItems() {
ArrayList<String> items = new ArrayList<String>();
for (int i = 0; i < nItems; i++) {
ListItem li = (ListItem) myItems.get(i);
items.add(li.getCaption());
}
return items;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item_row,
null);
holder.caption = (EditText) convertView
.findViewById(R.id.ItemCaption);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Fill EditText with the value you have in data source
holder.caption.setText(((ListItem) myItems.get(position)).caption);
// holder.caption.setText(myItems.get(position).caption);
holder.caption.setId(position);
// we need to update adapter once we finish with editing
holder.caption
.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
((ListItem) myItems.get(position)).caption = Caption
.getText().toString();
}
}
});
return convertView;
}
class ViewHolder {
EditText caption;
}
class ListItem {
String caption;
public String getCaption() {
return caption;
}
}
}
}
Could someone help me to solve this problem?
Are you sure your OnFocusChangeListener is called? If you edit the text in EditText then tap the confirm button, this listener will not be called in touch mode since the focus is still on the EditText.
Update: Consider the situation you edited the text in a EditText while didn't confirm and scrolled the ListView so that the item view is recycled, I'm not sure what is your preferred way, but if you want store the edited data, you can use setRecyclerListener(android.widget.AbsListView.RecyclerListener) to get notified when a item view is recycled so you can saved the edit result. To save the result of EditText showing on screen, you use methods like getChildAt to get item views visible on screen then get the EditText's text.
Update2: Another better and clean way is use TextWatcher and addTextChangeListener, this will notifies you when the text in EditText is changed.
Update3: I just write the following sample and test it, and it works on my phone. :)
Update4: I removed the previous code cause its performance is bad and creates a lot objects, you can check the following full sample instead:
Activity code :
package com.example.asynctasktest;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
/**
* #author Daniel Chow
*
* May 26, 2013 12:57:49 AM
*/
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listview);
final TestAdapter adapter = new TestAdapter(this);
listView.setAdapter(adapter);
Button confirmButton = (Button) findViewById(R.id.confirm_button);
confirmButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
List<String> items = adapter.getItems();
for (int i = 0, n = items.size(); i < n; i++) {
Log.e("", items.get(i));
}
}
});
}
#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;
}
}
Adapter code:
/**
*
*/
package com.example.asynctasktest;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
/**
* #author Daniel Chow
*
* May 26, 2013 1:13:02 AM */
public class TestAdapter extends BaseAdapter {
private List<String> items = new ArrayList<String>();
private Context context;
public TestAdapter(Context context) {
this.context = context;
for (int i = 0; i < 12; i++) {
items.add("caption " + i);
}
}
public List<String> getItems() {
return new ArrayList<String>(items);
}
#Override
public int getCount() {
return 12;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = new EditText(context);
holder = new ViewHolder();
holder.editText = (EditText) convertView;
holder.watcher = new EditTextWatcher();
holder.editText.addTextChangedListener(holder.watcher);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.watcher.setTarget(position);
holder.editText.setText(items.get(position));
return convertView;
}
private class EditTextWatcher implements TextWatcher {
private int target;
public void setTarget(int target) {
this.target = target;
}
#Override
public void afterTextChanged(Editable s) {
items.set(target, s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}
private static class ViewHolder {
EditText editText;
EditTextWatcher watcher;
}
}
I usually follow a simpler technique
public class Item_Adapter extends BaseAdapter {
private String[] Val;
public Item_Adapter () {
Val= new String[nItems];
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
///bla bla
holder.caption
.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
((ListItem) myItems.get(position)).caption = Caption
.getText().toString();
Val[position]= Caption
.getText().toString();
}
}
});
///bla bla
return convertView;
}
/////most important returning your array so you can use it in the Activity
public String[] getVal() {
return Val;
}

Android Adding OnClickListener to listview

I have been trying to create a settings app for my new rom called "ProtoType" and i am trying to add an OnClickListener to my listview but i cant find the appropriate way to do so and as a result i have turned to here for help and i was wondering if anybody can show me how i'll post my activity below and thanks.
package fr.xgouchet.tuto.switchpreferences;
import java.util.ArrayList;
import java.util.List;
import android.preference.PreferenceActivity;
import android.widget.ListAdapter;
public class MyPrefsActivity extends PreferenceActivity {
private List<Header> mHeaders;
protected void onResume() {
super.onResume();
setTitle("Settings");
if (getListAdapter() instanceof MyPrefsHeaderAdapter)
((MyPrefsHeaderAdapter) getListAdapter()).resume();
}
protected void onPause() {
super.onPause();
if (getListAdapter() instanceof MyPrefsHeaderAdapter)
((MyPrefsHeaderAdapter) getListAdapter()).pause();
}
public void onBuildHeaders(List<Header> target) {
// Called when the settings screen is up for the first time
// we load the headers from our xml description
loadHeadersFromResource(R.xml.my_prefs_headers, target);
mHeaders = target;
}
public void setListAdapter(ListAdapter adapter) {
int i, count;
if (mHeaders == null) {
mHeaders = new ArrayList<Header>();
// When the saved state provides the list of headers,
// onBuildHeaders is not called
// so we build it from the adapter given, then use our own adapter
count = adapter.getCount();
for (i = 0; i < count; ++i)
mHeaders.add((Header) adapter.getItem(i));
}
super.setListAdapter(new MyPrefsHeaderAdapter(this, mHeaders));
}
}
On PreferenceActivity listView is hiddent behind getListView();
The simpliest example:
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View view, int i, long l) {
Toast.makeText(Activity.this, "myPos "+i, Toast.LENGTH_LONG).show();
}
});
Code will look like
package fr.xgouchet.tuto.switchpreferences;
import java.util.ArrayList;
import java.util.List;
import android.preference.PreferenceActivity;
import android.widget.ListAdapter;
public class MyPrefsActivity extends PreferenceActivity {
private List<Header> mHeaders;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View view, int i, long l) {
Toast.makeText(Activity.this, "myPos "+i, Toast.LENGTH_LONG).show();
}
});
}
protected void onResume() {
super.onResume();
setTitle("Settings");
if (getListAdapter() instanceof MyPrefsHeaderAdapter)
((MyPrefsHeaderAdapter) getListAdapter()).resume();
}
protected void onPause() {
super.onPause();
if (getListAdapter() instanceof MyPrefsHeaderAdapter)
((MyPrefsHeaderAdapter) getListAdapter()).pause();
}
public void onBuildHeaders(List<Header> target) {
// Called when the settings screen is up for the first time
// we load the headers from our xml description
loadHeadersFromResource(R.xml.my_prefs_headers, target);
mHeaders = target;
}
public void setListAdapter(ListAdapter adapter) {
int i, count;
if (mHeaders == null) {
mHeaders = new ArrayList<Header>();
// When the saved state provides the list of headers,
// onBuildHeaders is not called
// so we build it from the adapter given, then use our own adapter
count = adapter.getCount();
for (i = 0; i < count; ++i)
mHeaders.add((Header) adapter.getItem(i));
}
super.setListAdapter(new MyPrefsHeaderAdapter(this, mHeaders));
}
}
I think it should be implemented in your adapter. This is example of a custom adapter. You can specify settings and listeners for elements in items.
/** Provides the custom adapter for views of words */
private class WordAdapter extends ArrayAdapter<DTOWord> {
Context context;
int layoutResourceId;
ArrayList<DTOWord> wordsArray;
/** Set up words data */
public WordAdapter(Context context, int layoutResourceId,
ArrayList<DTOWord> words)
{
super(context, layoutResourceId, words);
this.context = context;
this.layoutResourceId = layoutResourceId;
this.wordsArray = words;
}
#Override
/** Returns a view with a word */
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
LayoutInflater inflater = ((Activity) context).
getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
}
return this.getView(row, this.wordsArray.get(position));
}
/** Set up the view of the word with specified data */
private View getView(View wordView, final DTOWord wordData)
{
View container = (View) wordView.findViewById(R.id.
layout_wordData);
TextView title = (TextView) wordView.findViewById(R.id.
textView_word);
Button btnEditWord = (Button) wordView.findViewById(R.id.
btn_wordEdit);
this.setEditListener(btnEditWord, wordData);
return wordView;
}
/** Set action which switches to the edition view of the selected word */
private void setEditListener(Button btnEditWord, final DTOWord wordData) {
btnEditWord.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(WordAdapter.this.context,
AddWord.class);
i.putExtra("word-name", wordData.getWord());
i.putExtra("word-language", wordData.getLanguage().
getName());
startActivity(i);
}
});
}
}

Categories

Resources