I'm learning to program in android and I've stuck with this ... Someone should know how to make the items on the list are clickable? I will make a new view by passing the id parameter ...
Thank you very much.
This is my actual code:
public class ListaLugares extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_lugares);
ArrayList<Lugar> Lugares = getItems();
setListAdapter(new LugarAdapter(this, R.layout.lista_item, Lugares));
}
public ArrayList<Lugar> getItems() {
DatabaseHandler db = new DatabaseHandler(this);
ArrayList<Lugar> listaLugares = db.getAllLugares2();
db.close();
return listaLugares;
}
private class LugarAdapter extends ArrayAdapter<Lugar> {
private ArrayList<Lugar> items;
public LugarAdapter(Context context, int textViewResourceId, ArrayList<Lugar> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#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.lista_item, null);
}
Lugar lugar = items.get(position);
if (lugar != null) {
TextView tnombre = (TextView) v.findViewById(R.id.nombre);
TextView tdescripcion = (TextView) v.findViewById(R.id.descripcion);
if (tnombre != null) {
tnombre.setText(lugar.getNombre());
}
if (tdescripcion != null) {
tdescripcion.setText(lugar.getDescripcion());
}
}
return v;
}
}
}
You can override onListItemClick within your class, for instance, like in example you can call some other Activity:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Bundle positionBundle = new Bundle();
positionBundle.putInt("position", position);
Intent i = new Intent(this, MyOtherActivity.class);
i.putExtras(positionBundle);
startActivity(i);
}
Related
I need to change the clicked text in listview using a ProgramAdapter.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
String[] programName = {"ex1", "ex2", "ex3"}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvProgram = findViewById(R.id.listView);
ProgramAdapter programAdapter = new ProgramAdapter(this, programName);
lvProgram.setAdapter(programAdapter);
}}
ProgramAdapter.java:
public class ProgramAdapter extends ArrayAdapter<String> {
Context context;
String[] programName;
public ProgramAdapter(Context context, String[] programName) {
super(context, R.layout.single_item2, R.id.titulo, programName);
this.context = context;
this.programName = programName;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View singleItem = convertView;
ProgramViewHolder holder = null;
if(singleItem == null){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
singleItem = layoutInflater.inflate(R.layout.single_item2, parent, false);
holder = new ProgramViewHolder(singleItem);
singleItem.setTag(holder);
}
else{
holder = (ProgramViewHolder) singleItem.getTag();
}
holder.programTitle.setText(programName[position]);
}
}
My attempt was that:
ProgramViewHolder finalHolder = holder;
singleItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(programName[position] == "ex1") {
finalHolder.programTitle.setText("expected text");
}
}
});
This changes the text for a moment, but every time you go down the list and up again, the text goes back to the default text.
I would like someone to click on an item in my ListView and then my new activity would start and the text of the item they clicked on should be set as the text of the TextView in my new activity. Currently with the following code, my TextView result is:
'com.example.draft.AnimalNames#31571cf'
Here is what I have in MainActivity.java:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String clickedName = (list.getItemAtPosition(position).toString());
Intent intent = new Intent(MainActivity.this, Profile.class);
intent.putExtra("clickedName", clickedName);
startActivity(intent);
System.out.println(clickedName);
}
});
And in my new activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_layout);
Intent intent = getIntent();
String clickedName = intent.getStringExtra("clickedName");
animalName = findViewById(R.id.textView);
animalName.setText(clickedName);
}
And in my AnimalNames.java file:
public class AnimalNames {
private String animalName;
public AnimalNames(String animalName) {
this.animalName = animalName;
}
public String getanimalName() {
return this.animalName;
}
}
I don't think it's relevant to my question but here is my ListViewAdapter.java file:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<AnimalNames> animalNamesList; // Declare a null variable
private ArrayList<AnimalNames> arraylist; // Declare a null array
public ListViewAdapter(Context context, List<AnimalNames> animalNamesList) {
mContext = context;
this.animalNamesList = animalNamesList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<AnimalNames>();
this.arraylist.addAll(animalNamesList);
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return animalNamesList.size();
}
#Override
public AnimalNames getItem(int position) {
return animalNamesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_view_items, null); // Locate the TextViews in list_view_items.xml
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.name.setText(animalNamesList.get(position).getanimalName());
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
animalNamesList.clear();
if (charText.length() == 0) {
animalNamesList.addAll(arraylist);
} else {
for (AnimalNames wp : arraylist) {
if (wp.getanimalName().toLowerCase(Locale.getDefault()).contains(charText)) {
animalNamesList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
String clickedName = (list.getItemAtPosition(position).toString());
By calling toString() method, it will give you the object reference, which is what you get in the TextView.
According to your code, if you wish to see the Animal name, you should do (and fix the method name to getAnimalName):
String clickedName = ((AnimalNames)list.getItemAtPosition(position)).getanimalName();
getItemAtPosition() returns an Object, so you need to cast it to the correct class.
I created listView. enter image description here
And my adapter, which has a button, textView.enter image description here
I want to when i click on an button was removed element from the list.
How in the class MainActiviti access to the elements of another layout?
public class AdapterItem extends BaseAdapter {
Context context;
LayoutInflater lInflater;
ArrayList<ItemInList> items;
public AdapterItem(Context context, ArrayList<ItemInList> items){
this.context = context;
this.items = items;
lInflater = (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 view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
ItemInList itemInList = getItemList(position);
((TextView) view.findViewById(R.id.id_item)).setText(itemInList.id);
((TextView) view.findViewById(R.id.name)).setText(itemInList.name);
((ImageButton) view.findViewById(R.id.imageButton)).setImageResource(itemInList.imageButton);
return view;
}
ItemInList getItemList(int position) {
return ((ItemInList) getItem(position));
}
}
ItemInList.java
public class ItemInList {
String name;
String id;
int imageButton;
boolean deleteChek;
public ItemInList(String name, String id, int imageButton, boolean deleteChek){
this.name = name;
this.id = id;
this.imageButton = imageButton;
this.deleteChek = deleteChek;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ArrayList<ItemInList> arrayItemInLists = new ArrayList<ItemInList>();
AdapterItem adapterItem;
ListView listViewl;
Button delete;
Button checkAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fillData();
listViewl = (ListView) findViewById(R.id.listView);
delete = (Button) findViewById(R.id.delete_select);
checkAll = (Button) findViewById(R.id.select_all);
adapterItem = new AdapterItem(this, arrayItemInLists);
listViewl.setAdapter(adapterItem);
}
public void fillData() {
for (int i = 1; i <= 20; i++) {
arrayItemInLists.add(new ItemInList("String" + i," " + i, R.drawable.delete,false));
}
}
You need just remove an item from your DATA (in your case - arrayItemInLists) and call notifyDataSetChanged(). In fact you can do that inside an Adapter.
private OnClickListener listener= new OnClickListener() {
#Override
public void onClick(View v) {
int position = ((Integer) v.getTag());
}
};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
ItemInList itemInList = getItemList(position);
((TextView) view.findViewById(R.id.id_item)).setText(itemInList.id);
((TextView) view.findViewById(R.id.name)).setText(itemInList.name);
((ImageButton) view.findViewById(R.id.imageButton)).setImageResource(itemInList.imageButton);
((ImageButton) view.findViewById(R.id.imageButton)).setTag(position);
((ImageButton) view.findViewById(R.id.imageButton)).setOnClickListener(listener);
return view;
}
here is the code for custom listview using BaseAdapter in android its working fine:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<TaskClass> _listData;
Context _c;
public CustomListAdapter(Context context, ArrayList<TaskClass> listData) {
_listData = listData;
_c = context;
}
#Override
public int getCount() {
return _listData.size();
}
#Override
public Object getItem(int position) {
return _listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position,View convertView,ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater layoutInflator = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflator.inflate(R.layout.listview_row, null);
}
TextView titleText = (TextView)v.findViewById(R.id.holdTitleText);
TextView catText = (TextView)v.findViewById(R.id.holdCatText);
TextView descText = (TextView)v.findViewById(R.id.holdDescText);
TextView dateText = (TextView)v.findViewById(R.id.holdDateText);
//CheckBox checkBoxForEachItem = (CheckBox)v.findViewById(R.id.)
TaskClass taskClassInstance = _listData.get(position);
titleText.setText(taskClassInstance.getTitle());
catText.setText(taskClassInstance.getTaskCategory());
descText.setText(taskClassInstance.getDescription());
dateText.setText(taskClassInstance.getTaskDate());
return v;
}
}
and in activity i m binding listview with custom adapter :
listViewInstance.setAdapter(new CustomListAdapter(getApplicationContext(),taskClasslistInstance));
where "taskclasslistinstance" is my arraylist conatining data from DB its working fine
now i need to write function for listitemclick so that when user click on any listitem i can get rowid of that listitem record from Database.so after getting rowwid I can delete records from listview and from db and can edit informations
Well, we don't know about your TaskClass, but I expect you want something like this:
listViewInstance.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
TaskClass taskClass = taskClasslistInstance.get(pos);
Log.d(TAG, "Clicked on: " + taskClass)
// Do stuff with taskClass
}});
Here a small example from my project:
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LazyAdapterAlbum(getActivity(), songs);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(), AlbumActivity.class);
Bundle args = new Bundle();
args.putString(AlbumActivity.ALBUM_NAME, adapter.getItem(position).getName());
i.putExtras(args);
startActivity(i);
}
});
You have to set an onClickListener on your ListView.
you can also set in getView method like below:
public View getView(int position,View convertView,ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater layoutInflator = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflator.inflate(R.layout.listview_row, null);
}
TextView titleText = (TextView)v.findViewById(R.id.holdTitleText);
TextView catText = (TextView)v.findViewById(R.id.holdCatText);
TextView descText = (TextView)v.findViewById(R.id.holdDescText);
TextView dateText = (TextView)v.findViewById(R.id.holdDateText);
//CheckBox checkBoxForEachItem = (CheckBox)v.findViewById(R.id.)
TaskClass taskClassInstance = _listData.get(position);
titleText.setText(taskClassInstance.getTitle());
catText.setText(taskClassInstance.getTaskCategory());
descText.setText(taskClassInstance.getDescription());
dateText.setText(taskClassInstance.getTaskDate());
v.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform an action when this list item is clicked
}
});
return v;
}
i have problem with listview... i'm trying to add OnClickListener but in still doesn't work. I want to display another activity after click. Can somebody help me? I know that there are many of example, but it's doesn't work for my appl or i don't know how to use it in my example...
This is my LocationAdapter class:
public class LocationAdapter extends ArrayAdapter<LocationModel> {
int resource;
String response;
Context context;
private LayoutInflater mInflater;
public LocationAdapter(Context context, int resource, List<LocationModel> objects) {
super(context, resource, objects);
this.resource = resource;
mInflater = LayoutInflater.from(context);
}
static class ViewHolder {
TextView titleGameName;
TextView distanceGame;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
//Get the current location object
LocationModel lm = (LocationModel) getItem(position);
//Inflate the view
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.titleGameName = (TextView) convertView
.findViewById(R.id.it_location_title);
holder.distanceGame = (TextView) convertView
.findViewById(R.id.it_location_distance);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleGameName.setText(lm.getGameName());
holder.distanceGame.setText(lm.getGameDistance()+" km");
return convertView;
}
}
This is my mainListView class:
public class SelectGameActivity extends Activity {
LocationManager lm;
GeoPoint userLocation;
ArrayList<LocationModel> locationArray = null;
LocationAdapter locationAdapter;
LocationList list;
ListView lv;
TextView loadingText;
TextView sprawdz;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectgame);
lv = (ListView) findViewById(R.id.list_nearme);
locationArray = new ArrayList<LocationModel>();
locationAdapter = new LocationAdapter(SelectGameActivity.this, R.layout.item, locationArray);
lv.setTextFilterEnabled(true);
lv.setAdapter(locationAdapter);
lv.setItemsCanFocus(true);
String serverName = getResources().getString(R.string.serverAdress);
ApplicationController AC = (ApplicationController)getApplicationContext();
String idPlayer = AC.getIdPlayer();
int latitude = AC.getCurrentPositionLat();
int longitude = AC.getCurrentPositionLon();
int maxDistance = 99999999;
try {
new LocationSync().execute("myserverName");
} catch(Exception e) {}
}
//this is connection with json
private class LocationSync extends AsyncTask<String, Integer, LocationList> {
protected LocationList doInBackground(String... urls) {
LocationList list = null;
int count = urls.length;
for (int i = 0; i < count; i++) {
try {
// ntar diganti service
RestClient client = new RestClient(urls[i]);
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String json = client.getResponse();
list = new Gson().fromJson(json, LocationList.class);
//
} catch(Exception e) {}
}
return list;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(LocationList loclist) {
for(LocationModel lm : loclist.getLocations())
{
locationArray.add(lm);
}
locationAdapter.notifyDataSetChanged();
}
}
EDIT:: I have second problem... i want to get id from item (items are downloading from json url) This is my list:
I want to get for example: ID:159 for first item and send it to nextActivity.
I have also the controllerClass.java where i'm setting and getting selectedIdGame:
public String getIdGameSelected() {
return idGame;
}
public void setIdGameSelected(String idGame) {
this.idGame = idGame;
}
Is it good idea? Thanks for help.
Ok, it's done. i used:
public void onItemClick(AdapterView<?> a, View
v, int position, long id) {
String idGame = (String) ((TextView) v.findViewById(R.id.idGameSelected)).getText();
Thanks, Michal.
You could define an onItemClick on your adapter instance (i.e. in mainListView.java, just after lv.setAdapter):
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View
v, int position, long id) {
Intent i = new Intent(v.getContext(), NextActivity.class);
startActivity(i);
}
});
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Intent i = new Intent(view.getContext(), NextActivity.class);
startActivity(i);
}
});
I don't know why this wouldn't work, put it after the try{}catch{} block.