I would like to open an activity for each of my listview items. Done some research around onitemclickListener but don't know quite how to fit in with my current code.
My activities are called:
BhutanInfo.java
ColumbiaInfo.java
My listview is set up in an xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="country_names">
<item>Bhutan</item>
<item>Colombia</item>
</string-array>
<array name="country_icons">
<item>#drawable/bhutan</item>
<item>#drawable/colombia</item>
</array>
</resources>
In my class file I have the following:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Context ctx = getApplicationContext();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.country_names);
TypedArray icons = res.obtainTypedArray(R.array.country_icons);
setListAdapter(new ImageAndTextAdapter(ctx, R.layout.main_list_item, options, icons));
}
I also have another class which sets the adapter.
public class ImageAndTextAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;
public ImageAndTextAdapter(Context ctx, int viewResourceId,
String[] strings, TypedArray icons) {
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater)ctx.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mIcons = icons;
mViewResourceId = viewResourceId;
}
#Override
public int getCount() {
return mStrings.length;
}
#Override
public String getItem(int position) {
return mStrings[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon);
iv.setImageDrawable(mIcons.getDrawable(position));
TextView tv = (TextView)convertView.findViewById(R.id.option_text);
tv.setText(mStrings[position]);
return convertView;
}
Any help would be appreciated.
if you had only two items means you can redirect the activity based on the position and you can perform this way
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String str = parent.getItemAtPosition(position).toString();
Log.e("Clicked Value is", str);
if(str.equals("<Your Class Name>")){
startActivity(new Intent(MainActivity.this,
FirstActivity.class);
}else{
startActivity(new Intent(MainActivity.this,
Second.class);
}
}
});
In this scenario you used custom adapter, i am right.
so you can manage click listener in custom adapter,
if you don't want this scenario, then you have to
android:focusableInTouchMode="false"
in you custom list row in xml file, and then call then listview onclick listener it will work.
in your ActivityClass, have the listView implement the onItemClickListener.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String value = options[position];
if(value.equals("Bhutan")){
Intent intent = new Intent(CurrentActivity.this, BhutanInfo.class);
startActivity(intent);
}else if(value.equals("Columbia")){
intent = new Intent(CurrentActivity.this, ColumbiaInfo.class);
startActivity(intent);
}
}
});
P.S: Ensure that BhutanInfo and ColumbiaInfo are extending Activity.
And in the row layout inflating the listview set focusable and focusableInTouchMode to false for all the elements in it.
Related
So I have a program where I need to display a different toast depending on what item the user selects in a list. I created a custom adapter since I need to add pictures to the list and created an object that goes by the name Day that contains the day of the week, the image, and the custom text that needs to go in the toast. My problem is that I don't know how to create an onItemClickListener that will use my custom text for my toast.
This is my custom adapter
public class DayAdapter extends ArrayAdapter<Day> {
private Context mContext;
int mResource;
public DayAdapter(#NonNull Context context, int resource, #NonNull ArrayList<Day> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
String jour = getItem(position).getDay();
int image = getItem(position).getImage();
String message = getItem(position).getMessage();
Day journee = new Day(jour, image, message);
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
TextView tvJour = (TextView) convertView.findViewById(R.id.textViewJour);
ImageView tvImage = (ImageView) convertView.findViewById(R.id.imageViewJour);
tvJour.setText(jour);
tvImage.setImageResource(image);
return convertView;
}
This is my MainActivity
public class MainActivity extends AppCompatActivity {
ListView liste;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
liste = (ListView) findViewById(R.id.dayList);
ArrayList<Day> semaine = new ArrayList<Day>();
Day lundi = new Day("Lundi", R.drawable.happyface, "Prog lundi");
Day mardi = new Day("Mardi", R.drawable.happyface, "Musique mardi");
Day mercredi = new Day("Mercredi", R.drawable.happyface, "Mercredi");
Day jeudi = new Day("Jeudi", R.drawable.beer, "Work jeudi");
Day vendredi = new Day("Vendredi", R.drawable.beer, "also work vendredi");
Day samedi = new Day("Samedi", R.drawable.malade, "also also work samedi");
Day dimanche = new Day("Dimanche", R.drawable.etude, "Love Dimanche");
semaine.add(lundi);
semaine.add(mardi);
semaine.add(mercredi);
semaine.add(jeudi);
semaine.add(vendredi);
semaine.add(samedi);
semaine.add(dimanche);
DayAdapter adapter = new DayAdapter (this, R.layout.row, semaine);
liste.setAdapter(adapter);
liste.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String messa = adapterView.getAdapter().getItem(i).toString();
Toast.makeText(MainActivity.this, messa, Toast.LENGTH_LONG).show();
}
});
}
}
Try making the Toast in your ArrayAdapter class, specifically in the getView method like
convertview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, "Custom Toast", Toast.LENGTH_SHORT).show();
}
});
If you want, you can use an onTouchListener instead of the onClickListener.
I have created android app like gallery which have some images using gridview fragment.
Functionality of my application is working fine and image showing in fragment gridview and also my second activity open when i click on item but i want to show cardview GridView with Animations.
Also if it is easier default image in place of loading images instead of progress bar will be fine.
Here is my application fragment code :
public class CallFragment extends Fragment {
GridView grid;
String[] plan = {
"Student Bundle",
"SMS Plus Bundle",
"Instagram",
"Facebook",
"Flickr"
} ;
String[] web = {
"*3000",
"*106*1",
"Instagram",
"Facebook",
"Flickr"
} ;
int[] imageId = {
R.drawable.calla,
R.drawable.smsb,
R.drawable.person7,
R.drawable.person7,
R.drawable.person7
};
int[] fullimg = {
R.drawable.callaa,
R.drawable.smsbb,
R.drawable.person7,
R.drawable.person7,
R.drawable.person7
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_call,container,false);
CustomGrid adapter = new CustomGrid(getActivity(), plan, web, imageId, fullimg);
grid=(GridView) view.findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String value=(String)grid.getItemAtPosition(i);
Intent intent=new Intent(getActivity(),Book.class);
intent.putExtra("web", web[i]);
intent.putExtra("plan", plan[i]);
intent.putExtra("imageId", imageId[i]);
intent.putExtra("fullimg", fullimg[i]);
startActivity(intent);
}
});
return view;
}
Here is my application CustomAdapter code :
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
ArrayList<String> personNames;
ArrayList<String> personCode;
ArrayList<Integer> personImages;
ArrayList<Integer> personImages1;
Context context;
public CustomAdapter(Context context, ArrayList<String> personNames, ArrayList<String> personCode, ArrayList<Integer> personImages, ArrayList<Integer> personImages1) {
this.context = context;
this.personCode = personCode;
this.personNames = personNames;
this.personImages = personImages;
this.personImages1 = personImages1;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// infalte the item Layout
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
// set the data in items
//holder.name.setText(personNames.get(position));
holder.image.setImageResource(personImages.get(position));
//holder.image.setImageResource(personImages1.get(position));
// implement setOnClickListener event on item view.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// open another activity on item click
Intent intent = new Intent(context, SecondActivity.class);
//intent.putExtra("image", personImages.get(position)); // put image data in Intent
intent.putExtra("name", personNames.get(position)); // put image data in Intent
intent.putExtra("code", personCode.get(position)); // put image data in Intent
intent.putExtra("image", personImages1.get(position)); // put image data in Intent
context.startActivity(intent); // start Intent
}
});
}
#Override
public int getItemCount() {
return personNames.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// init the item view's
TextView name;
TextView code;
ImageView image;
public MyViewHolder(View itemView) {
super(itemView);
// get the reference of item view's
name = (TextView) itemView.findViewById(R.id.name);
code = (TextView) itemView.findViewById(R.id.code);
image = (ImageView) itemView.findViewById(R.id.image);
}
}
}
Here is example of my requirement :
My gridview looks like this :
Create an separate XML file under anim and apply in the onBindViewHolder.
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
// Here you apply the animation when the view is bound
setAnimation(holder.itemView, position);
}
/**
* Here is the key method to apply the animation
*/
private void setAnimation(View viewToAnimate, int position)
{. int lastPosition=0;
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
}
You can apply animations on RecyclerView using this tutorial.
and for default image just put a src property inside your imageview in R.layout.rowlayout XML file
Used this Recyclerview with Load animation
Recyclerview Load Animation
I am using the following code to display images on ListView using BaseAdapter .The code displays images from inside drawable folder. But I want to modify the code so it displays remote images from following Array:
String flags[] ={"http://www.website.com/images/usa.png","http://www.website.com/images/china.png","http://www.website.com/images/australia.png","http://www.website.com/images/portugle.png","http://www.website.com/images/norway.png","http://www.website.com/images/new_zealand.png"};
Could an expert show me what part needs to be change.Thanks in advance.
MainActivity.java:
public class MainActivity extends Activity {
ListView simpleList;
String countryList[] = {"USA", "China", "australia", "Portugle", "Norway", "NewZealand"};
int flags[] = {R.drawable.usa, R.drawable.china, R.drawable.australia, R.drawable.portugle, R.drawable.norway, R.drawable.new_zealand};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleList = (ListView) findViewById(R.id.simpleListView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), countryList, flags);
simpleList.setAdapter(customAdapter);
simpleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Hello " + countryList[position], Toast.LENGTH_LONG).show();
}
});
}
}
CustomAdapter.java:
Public class CustomAdapter extends BaseAdapter {
Context context;
String countryList[];
int flags[];
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, String[] countryList, int[] flags) {
this.context = context;
this.countryList = countryList;
this.flags = flags;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return countryList.length;
}
#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) {
view = inflter.inflate(R.layout.activity_listview, null);
TextView country = (TextView) view.findViewById(R.id.textView);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
country.setText(countryList[i]);
icon.setImageResource(flags[i]);
return view;
}
}
You need to:
1) Fetch those images in a separate thread, you can use volley, retrofit, robospice for this.
2) On the response of any of those methods from 1) you have to pass the list of values you obtained from the service to your adapter's constructor. You will need to create a POJO for the model, this structure will hold all the elements from the REST webservice.
3) It is recommended to use a viewholder for your listview's adapter, to avoid inflating the views again and again.
The easiest thing to do is use Glide or Picasso:
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_listview, null);
TextView country = (TextView) view.findViewById(R.id.textView);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
country.setText(countryList[i]);
// Assuming flags is now the list of Strings of image urls
GlideApp.with(view.getContext()).load(flags[i]).into(icon);
return view;
}
you can also use some third party library like Picasso or Glide to load images right into your adapter's get view method
Picasso.with(this).load(flags[adapter's
position]).into(imageView);
same in glide.
here is simple tutorial https://www.simplifiedcoding.net/picasso-android-tutorial-picasso-image-loader-library/
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);
}
});
The problem is when the ListView loses focus, the selected item isn't highlighted.
I use a custom ArrayAdapter which uses the following layout for items:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ListTextBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="#dimen/Padding"
android:textSize="#dimen/TextSize"
/>
The ListSelector is a simple Shape drawable.
Thank you
edit...
Here is the ArrayAdapter:
listWords = new ArrayList<String>();
arrayAdapter = new DictListAdapter(this, R.layout.listtext, listWords);
list.setAdapter(arrayAdapter);
and the code for DictListAdapter:
public class DictListAdapter extends ArrayAdapter<String> {
public DictListAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
this.context = (MainWindow) context;
this.objects = objects;
this.res = textViewResourceId;
}
Typeface font;
private List<String> objects;
private final MainWindow context;
int res;
int gravity=Gravity.LEFT;
#Override
public int getCount() {
return objects.size();
}
#Override
public String getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String obj = objects.get(position);
TextView tv = new TextView(context, null, res);
tv.setText(obj);
tv.setTypeface(context.getFont());
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX,
context.getResources().getDimension(R.dimen.TextSize));
tv.setGravity(gravity);
return tv;
}
public void setGravity(int g){
this.gravity=g;
}
}
i guess you have created array adapter in the following manner. if i am correct use the following:
static final String[] color = new String[]{"red","green","blue"};
We need to use the setListAdapter(..) method of the ListActivity class to bid the two (data and view). Android provides many implementations of the ListAdapter. We will use the simple ArrayAdapter.
What does the ArrayAdapter expect?
It expects the context object, the row layout and the data in an array.
So here it is:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, PENS));
getListView().setTextFilterEnabled(true);
}
use below code to show selected item
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String pen = o.toString();
Toast.makeText(this, "You have chosen the color: " + " " + color, Toast.LENGTH_LONG).show();
}
The simplest way is to add android:background="?android:attr/activatedBackgroundIndicator" in the layout you use for the row