Android onclick listener custom listview - android

With the following code I'm correctly receiving a dynamic list from mysql db and putting the elements in a listview.
public class MenuActivity extends ListActivity implements FetchDataListener {
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
initView();
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading..");
String url = "http://www.*********.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
This is my array adapter:
public class ApplicationAdapter extends ArrayAdapter<Application>{
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.app_cat_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_cat_list, null);
}
Application app = items.get(position);
if(app != null) {
TextView titleText = (TextView)v.findViewById(R.id.titleTxt);
if(titleText != null) titleText.setText(app.getTitle());
}
return v;
}
Now I want to click on single row and open another activity passing some values via intent extra.
Where should I implement click listener?
I'm pretty sure it should be inserted in the "getView" but how I pass the app.getTitle() via intent? I know how pass intent extra in general, tried but no click happens.
Any help would be appreciated, thanks

Now I want to click on single row and open another activity passing
some values via intent extra. Where should I implement click listener?
No need to add OnItemClickListener because extending ListActivity in MenuActivity so just override onListItemClick method for handing ListView row click:
#Override
public void onListItemClick(ListView l, View view, int position, long id) {
// your code here...
}
how I pass the app.getTitle() via intent?
Get selected row TextView value in onListItemClick using view parameter:
TextView txtView=(TextView)v.findViewById(R.id.titleTxt);
String selectedText=txtView.getText().toString();
Use selectedText for sending value with Intent in Next Activity

Put this in your getView()
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent =new Intent(context, YourActivity.class);
context.startActivity(intent);
}
});

There can be multiple ways and following is one of them:
Set onItemClickListner on your listview in your activity and it will give you a callback i.e onListItemClick. But as you said you want the title their you have to set tag on the convertView in the getView method like covertView.setTag("itemTitle"); and in your onListItemClick get the tag from view and convert it to the title like this v.getTag().toString(); and set it any where you want.
follwoing is the full code:
#Override
public void onListItemClick(ListView l, View view, int position, long id) {
String title = view.getTag().toString();
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("title", title);
startActivity(intent);
// your code here... }
Please post if got stuck anywhere.

Related

Android : How to Pass the previous Activity Intent into a Listview

I have Two Activity ( Activity A, Activity B) In Activity A i have a EditText,Button and Image View And in Activity B i have a Listview and the listView View Contain CustomXml with ImageView,TextView,and Another TextView
in Activity A, i enter List Name in Edit Text (Ex : Apple) and i Chose One Image ina GridView (Ex an Apple Image )
and i pass Both the Edittext and ImageView to a new Activity Where i want to Display Those names in ListView (Apple and Apple Image) How to DO that
i want to display something like this ( i get the Grocery List and Image From the Previous Activity and i want to display in ListView( in listview i extra add the items Count TEXTVIEW)
firstActivity.Java
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemname = listname.getText().toString();
if (!TextUtils.isEmpty(listname.getText().toString())) {
startActivity(new Intent(getContext(), CheckslateHome.class).putExtra("data", itemname).putExtra("image", imageRes));
dismiss();
} else {
Toast.makeText(getContext(), "List Name not Empty ", Toast.LENGTH_SHORT).show();
}
}
});
Second Activity
public class CheckslateHome extends AppCompatActivity {
TextView listcounts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkslate_home);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String itemName= bundle.getString("data");
Int ItemImage = bundle.getString("Image");
**//How to Pass these Intents into the Custom ListView**
}
listcounts = findViewById(R.id.list_count);
ListView listView = findViewById(R.id.list1);
CustomAdpter customAdapter = new CustomAdpter();
listView.setAdapter(customAdapter);
}
public class CustomAdpter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
#Override
public int getCount() {
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = layoutInflater.inflate(R.layout.rowlayout, viewGroup, false);
}
ImageView imageicons = view.findViewById(R.id.image_list);
TextView listnames = view.findViewById(R.id.list_name);
return view;
}
}
I Highly suggest using a combination of Fragments and navigation, in this way you can easily navigate through your app and send values between fragments using safe-args plugin
but if you persist on using activity, you should use startActivityForResult to call second activity.

StartActivityForResoult on ListViewItem click Android

I have an activity lets call it Activity 1 and there we will have a ListView composed by Player objetcs. When you click on a ListView_item (on a Player) a new activity starts, lets call it Activity 2. What I want is:
Activity 1 sends to Activity 2 player's name and player's race. In Activity 2 the user could edit that (player's name and player's race) and when the user click on Confirm Ativity 2 sends to Activity 1 the player's name and player's race even I the user has not edited it (in that case it would send the previus that Activity 1 has sended to Activity 2).
The problem is that when I'm suposse to use startActivityForResult I'm into ListViewAdapter class and using context.start... startActivityForResult doesn't appears.
public class AdaptadorJugadores extends BaseAdapter implements ListAdapter {
private ArrayList<Jugador> list = new ArrayList<Jugador>();
private Context context;
public AdaptadorJugadores(ArrayList<Jugador> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.item_lista_jugadores, null);
}
//Handle TextView and display string from your list
TextView TextoNombreJugador = (TextView)view.findViewById(R.id.etNombreJugador);
TextoNombreJugador.setText(list.get(position).getNombre());
if (list.get(position).getGenero() == "Hombre"){
TextoNombreJugador.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_face_black_24dp, 0, 0, 0);
}else{
TextoNombreJugador.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_face_black_girl24dp, 0, 0, 0);
}
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.btEliminarJugador);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
/*addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
}
});*/
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(context, VistaJugador.class);
intent.putExtra("Nombre",(list.get(position).getNombre()));
intent.putExtra("Genero",(list.get(position)).getGenero());
// Start SingleItemView Class
}
});
return view;
}
}
You could use the ListView's setOnItemClickListener(AdapterView.OnItemClickListener listener) method and in there you could start the activity using startActivityForResult.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the data to pass to the activity based on the position clicked
Intent intent = new Intent(...);
intent.setExtra(...);
startActivityForResult(...);
}
});
Alternatively, you could pass the Activity to your adapter and use that instead of a context, but the first solution is preferable.
I suggest you to pass the context from the Activity to the Adapter, then store it in a local variable. After that, you can just use it to startActivityForResult, but note that you have to implement the onActivityResultMethod. My suggestion is that you use an interface, then pass the ID of the selected item and call the startActivityForResult() in the Activity.

On Item Click Listener for List View extending ArrayAdapter

What I have tried:
public class EntryAdapter extends ArrayAdapter<Item> {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
// // // // NON-FUNCTIONING CODE BELOW
AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), NewsItemActivity.class);
convertView.getContext().startActivity(intent);
}
};
}
The AdapterView.onItemClickListener doesnt yield any errors but doesnt seem to function whatsoever.
What is the proper way of setting this onClick Listener?
Note: I have to set it in this adapter class, not the main class for my own reasons.
You shuldn't implement a listener inside the getView() unless you what set a listener on a particular view inside your row layout.
You should instead use setOnItemClickListener() method on your ListView:
ListView lv = (ListView) findViewById(R.id.your_listview);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(context, NewsItemActivity.class);
context.startActivity(intent);
}
});
EDIT:
If, for each action inside the onclick, you need information that resides in your Objects (Item) then you can get it in this way:
Item item = (Item)listview.getAdapter().getItem(position);
from inside of onItemClick() method
You can use:
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Make what you want
}
});
Or depending on your item view, you can make the OnCLickListener on your global layout of the item or a specific item's layout
Try by this code :-
Spinner cb_tv;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> dataAdapter;
list.add(phone1);
list.add(name1);
dataAdapter = new ArrayAdapter<String>(Display_Tank.this,android.R.layout.simple_spinner_item, list);
cb_tv.setAdapter(dataAdapter);
cb_tv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_SHORT).show();
}
});
at the place of cb_tv Spinner You can use ListView
First of all, the best way to achieve this is to use your own ViewHolders in ListView.
This is an example of a custom ViewHolder
class MyViewHolder extends ViewHolder implements View.OnItemClickListener {
public MyViewHolder(View view) {
/* Implement your views here
* like this: mTextView = (TextView) view.findViewById(R.id.myId);
*/
view.setOnItemClickListener(this);
}
#Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), NewsItemActivity.class);
convertView.getContext().startActivity(intent);
}
}
And on your getView method you create this ViewHolder and populate your Views with your data.
You can try this way... it is working in my case Change your context to
Activity activity = (Activity) context;
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, NewsItemActivity.class);
activity.startActivity(intent);
}
});

ListView (button not running)

Practicing on the ListView, I thought of adding buttons as well to it, rather than showing only content. But in my implementation, the button does not do anything at all.
Plus I was confused whether I could get the position of the button clicked. For now I am just sending the toSend declared inside the OnItemClick in an intent.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
final int toSend = position;
TextView refId = (TextView)view.findViewById(R.id.list_id);
TextView refName = (TextView)view.findViewById(R.id.list_name);
TextView refAdd = (TextView)view.findViewById(R.id.list_address);
Button edit = (Button)view.findViewById(R.id.edit);
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(ListActivity.this, EditLayout.class);
i.putExtra("position", toSend);
startActivity(i);
}
});
String sd_id = refId.getText().toString();
String sd_name = refName.getText().toString();
String sd_add = refAdd.getText().toString();
buildAlert(sd_id, sd_name, sd_add);
}
});
You're pretty close. The "inside" setOnClickListener needs to happen when you create the list row view (the view containing id, name, address, edit).
You can do that during getView(). But where to send the clicks? Instead of creating a new onClickListener, use "this" (your activity). Put an onClick() handler in the activity.
Then, when you get a click, the onClick method will execute. Next problem: how do you know which row clicked? The easiest way that comes to mind is to give the button a different id for e ach row - use the row index (you might need to start at 1 rather than 0 - be warned).
Finally, given the row id, it's easy to start your "nested" activity.
Hope this helps.
(added later)
I do it like this; you'll need to define a layout for your row view:
class MyActivity extends Activity implements View.OnClickListener
{
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.my_page);
ListView list = (ListView)findViewById (android.R.id.list);
MyArrayAdapter adapter = new MyArrayAdapter (this, <your array of data>);
list.setAdapter (adapter);
}
#Override
public void onClick(View v)
{
int buttonId = v.getId();
if (buttonId is within range)
... do what you need to do with the click ...
}
private class MyArrayAdapter extends ArrayAdapter<MyData>
{
private Activity act;
//-----------------------------------------------------------------------------
public MyArrayAdapter (Activity act, MyData array)
{
super (act, R.layout.list_row, array);
this.act = act;
}
//-----------------------------------------------------------------------------
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
ViewGroup rowView = (ViewGroup)convertView;
if (rowView == null)
{
LayoutInflater inflater = act.getLayoutInflater();
rowView = (ViewGroup) inflater.inflate (R.layout.list_row,
parent, false);
}
Button button = (Button)rowView.findViewById (R.id.is_member);
button.setId (position+1); // add one to avoid 0 as an id.
button.setOnClickListener (act);
// set field values here -- not shown
return rowView;
}
}
}

Moving Activity to another Activity when class extends ArrayAdapter

When I click the edit_remainder button I want to move my Activity to another Activity.
But where the class extends ArrayAdapter I don't understand how to move to another Activity.
Please help me with an example of the Intent class.
public class mylist extends ArrayAdapter<String> implements OnClickListener
{
private final Context context;
private final String[] values;
Button edit_remainder;
public mylist(Context context, String[] values) {
super(context, R.layout.some, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.buttonadd, parent, false);
edit_remeinder=(Button) rowView.findViewById(R.id.btnEdit);
edit_remeinder.setOnClickListener(this);
return rowView;
}
public void onClick(View v) {
Toast.makeText(getContext(), "hi", 1000).show();
// please enter moving code here
}
}
If I understand correctly, you wish to transfer control to another activity when the user taps on a list item. You will need to issue an intent.
Here's a tutorial: http://www.vogella.com/articles/AndroidIntent/article.html
launch an explicit intent here like:
Intent i=new Intent(context,anotheractivity.class);
startActivity(i);
here the context could be the application context.
Are you create your own adapter(mylist)?
If yes then pass the intent in your main class from you call the mylist adapter.
here I created for listview ,but you can try for your own application.
pass the intent in your main activity instead of your own adapter.
mainActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lview = (ListView) findViewById(R.id.listView2);
lviewAdapter = new ListViewAdapter(this, month, number); //here ListViewAdapter is my own adapter
System.out.println("adapter => "+lviewAdapter.getCount());
lview.setAdapter(lviewAdapter);
lview.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(this,"Title => "+month[position]+"=> n Description"+number[position], Toast.LENGTH_SHORT).show();
// here your intent code
}
}
please put this onclick method in your main activity and try again.
public void onClick(View v) {
Toast.makeText(getContext(), "hi", 1000).show();
// please enter moving code here
}

Categories

Resources