Android custom listview intents How to let it work? - android

I made a custom listView and custom array adapter with 1 image and 2 textviews. What I want to work is when you click on an item in the listview that it opens a new activity with an intent.
this is the mainactivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.?_main);
ListView listView = (ListView) findViewById(R.id.list);
ArrayList<Subjects> obsclassiclist = new ArrayList<Subjects>();
obsclassiclist.add(new Subjects("?", "?", R.mipmap.ic_launcher));
obsclassiclist.add(new Subjects("?", "?", R.mipmap.ic_launcher));
WordAdapter adapter = new WordAdapter(this, obsclassiclist);
listView.setAdapter(adapter);
LinearLayout listViewIntent = (LinearLayout) findViewById(R.id.intent);
listViewIntent.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
if (position==0) {
Intent tutorial = new Intent(view.getContext(),
Cl_01.class);
// Start the new activity
startActivityForResult(tutorial,0);
}
if (position==1) {
Intent requirements = new Intent(view.getContext(),
CL_02.class);
// Start the new activity
startActivityForResult(requirements,1);
}
}
});
}
}
this the custom adapter
public WordAdapter(Activity context, ArrayList<Subjects> subjects) {
// Here, we initialize the ArrayAdapter's internal storage for the context
and the list.
// the second argument is used when the ArrayAdapter is populating a single
TextView.
// Because this is a custom adapter for two TextViews and an ImageView, the
adapter is not
// going to use this second argument, so it can be any value. Here, we used
0.
super(context, 0, subjects);
}
/**
* Provides a view for an AdapterView (ListView, GridView, etc.)
*
* #param position The position in the list of data that should be displayed
in the
* list item view.
* #param convertView The recycled view to populate.
* #param parent The parent ViewGroup that is used for inflation.
* #return The View for the position in the AdapterView.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
// Get the {#link subject} object located at this position in the list
Subjects currentSubjects = getItem(position);
// Find the TextView in the list_item.xml layout with the ID subject
TextView subjectTextView = (TextView)
listItemView.findViewById(R.id.subject);
// Get the version name from the current wordadapter object and
// set this text on the subject TextView
subjectTextView.setText(currentSubjects.getObsclassicSubject());
// Find the TextView in the list_item.xml layout with the ID description
TextView descriptionTextView = (TextView)
listItemView.findViewById(R.id.description);
// Get the version number from the current wordadapter object and
// set this text on the description TextView
descriptionTextView.setText(currentSubjects.getObsclassicDescription());
// Find the Imageview in the list_item.xml layout with the ID version_number
ImageView pictureImageView = (ImageView)
listItemView.findViewById(R.id.image);
// Get the version number from the current wordadapter and
// set this image on the imageview
pictureImageView.setImageResource(currentSubjects.getObsclassicimageid());
// Return the whole list item layout (containing 2 TextViews and an
ImageView)
// so that it can be shown in the ListView
return listItemView;
}
}
here is the xml custom listview
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="#+id/intent"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/image"
android:scaleType="centerInside"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:textSize="20sp"
android:textStyle="bold"
android:id="#+id/subject"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:paddingBottom="10dp"
android:textSize="18sp"
android:textStyle="italic"
android:id="#+id/description"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
and the xml from the main activity
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list">
</ListView>
if somebody has a solution pls let me know

You are doing wrong, your are making clicklistener on linear layout, instead do it on ListView
Change this
listViewIntent.setOnItemClickListener(new
AdapterView.OnItemClickListener()
To
listView .setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Toast.makeText(SuggestionActivity.this, "" + position, Toast.LENGTH_SHORT).show();
// Now if you want to startActivity
Intent tutorial = new Intent(MainActivity.this,
Cl_01.class);
// Start the new activity
startActivityForResult(tutorial,position);
}
});

Related

Android custom ArrayAdapter rendering Objects in list, not values

I'm trying to bind a custom layout (a LinearLayout containing two TextViews) to a Spinner. I subclassed ArrayAdapter (mostly) correctly. Selecting an item in the Spinner calls getView() correctly, setting the LinearLayout's TextViews' values correctly. The problem is the initial display of the items in the Spinner (when clicking on the Spinner) just shows Objects; not the TextViews they should be displaying. Only AFTER clicking on one of the Objects does the Spinner correctly set the TextViews using my custom adapter's getView() method. Here's the custom adapter class:
public class BusRouteAdapter extends ArrayAdapter<BusRoute> {
...
public BusRouteAdapter(Context context, int resource, int textViewId, ArrayList<BusRoute> routes) {
super(context, resource, textViewId, routes);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
BusRoute route = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.bus_route, parent, false);
}
TextView tvBusRoute = (TextView) convertView.findViewById(R.id.tvBusRoute);
TextView tvBusRouteNumber = (TextView) convertView.findViewById(R.id.tvBusRouteNumber);
tvBusRoute.setText(route.routeName);
tvBusRoute.setTag(route.route);
tvBusRouteNumber.setText(route.route);
if (!route.routeColor.equals("")) {
tvBusRouteNumber.setBackgroundColor(Color.parseColor(route.routeColor));
}
return convertView;
}
}
Here's the layout that is to be used for each Spinner list item (bus_route.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="#+id/tvBusRouteNumber"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.25"
android:padding="8dp" />
<TextView
android:id="#+id/tvBusRoute"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.75"
android:padding="8dp" />
</LinearLayout>
And in my Activity, I'm setting the adapter to a properly-populated list of BusRoute objects:
busRouteAdapter = new BusRouteAdapter(getBaseContext(), R.layout.bus_route, R.id.tvBusRoute, arrayOfBusRoutes);
routesSpinner.setAdapter(busRouteAdapter);
It does seem strange that I need to pass the Layout id (R.layout.bus_route) AND one of the TextViews contained in that Layout (R.id.tvBusRoute).
Here's what is rendered when clicking on the Spinner:
But if I click one of the Objects, getView() is called, and the selected Layout and TextViews are rendered properly (apparently I selected "GMU - Pentagon"):
What am I missing to get the Spinner's popup list to display ALL my bus route items rendered correctly?
I think you need to override getDropDownView to deal with spinners
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
BusRoute route = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.bus_route, parent, false);
}
TextView tvBusRoute = (TextView) convertView.findViewById(R.id.tvBusRoute);
TextView tvBusRouteNumber = (TextView) convertView.findViewById(R.id.tvBusRouteNumber);
tvBusRoute.setText(route.routeName);
tvBusRoute.setTag(route.route);
tvBusRouteNumber.setText(route.route);
if (!route.routeColor.equals("")) {
tvBusRouteNumber.setBackgroundColor(Color.parseColor(route.routeColor));
}
return convertView;
}

setOnItemClickListener doesn't work on Fragment

I have a class that extends Fragment. I have a ListView. When I click on an item, it return always the same item.
Here the row.xml of the ListView adapter.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:id="#+id/IdItem"/>
</LinearLayout>
And here the event:
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
myTextView = (TextView)getActivity().findViewById(R.id.IdItem);
String IdItem = myTextView.getText().toString();
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra("IdItem", IdItem);
startActivity(intent);
}
});
It always returns the same IdItem, and not the choosen one.
Change this:
myTextView = (TextView)getActivity().findViewById(R.id.IdItem);
for this:
myTextView = view.findViewById(R.id.IdItem);
The rows objects of a ListView are reused in order to save memory, so you need to use the View object being sent in the onItemClick method of the ListView. This View object represents the actual clicked row inside the ListView with current child Views and values.

Using customlistviews in android : Keep on getting list view = NULL

I am new to android and am trying to create two fragments and have it so you can slide between the two, one is a list and the otehr a grid. I had the list working when it when I was using an ArrayAdapter and had my EventListFragment extending ListFragment (if code is helpful let me know and ill post that part)
I am now trying to create a custom list view with multiline list items (let me know if there is an easier way and if i have simply overcomplicated the whole thing)
Here is my code:
Event List Fragment:
public class EventListFragment extends Fragment {
ArrayList<EventObject> eventObjects;
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
eventObjects = ((EventsActivity)getActivity()).getEventObjects();
View view = inflater.inflate(R.layout.eventgrid ,container,false);
Listview listView = (ListView) view.findViewById(R.id.listView);
if (listView == null) {
System.out.println("asas");
}
listView.setAdapter(new MyCustomBaseAdapter(getActivity().getBaseContext(), eventObjects));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = listView.getItemAtPosition(position);
EventObject fullObject = (EventObject)o;
System.out.println("asd");
}
});
return view;
}
}
The corresponding xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<ListView
android:id="#+id/listView"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</RelativeLayout>
The xml for the customgridrow:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/name"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#FFFF00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/cityState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
EDIT
The getView() from MyCustomBaseAdapter :
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.customgridrow, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtCityState = (TextView) convertView.findViewById(R.id.cityState);
holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(events.get(position).getName());
holder.txtCityState.setText(events.get(position).getDate());
holder.txtPhone.setText(events.get(position).getVenue());
return convertView;
}
From your comments
You are inflating the wrong layout
You should inflate the one that has listview and initialize the same.
Change
View view = inflater.inflate(R.layout.eventgrid ,container,false);
to
View view = inflater.inflate(R.layout.eventList ,container,false);
Every time you want to add an object to a list, you have to provide a view for the object. Android asks your list adapter, be it custom or system-defined, it asks the adapter what each list item is supposed to look like. This is where getView() comes into play.
public abstract View getView (int position, View convertView, ViewGroup parent):
Get a View that displays the data at the specified position in the data set.
If convertView is null, you will get an NPE.
Tutorials here: http://www.javacodegeeks.com/2013/06/android-listview-tutorial-and-basic-example.html

Adding image to listview after listview item click

I am developing an app which has a listView having 1 textView which displays the content and one imageView. What i want is, when i click the listView i want to set the imageView with the tick mark image which i have. Its working fine. Once i click the listView, the tick mark image is loaded on that listview item on which i clicked.
The problem arises when i scroll. When i scroll, i could see some other listview item down below has a tick mark loaded. not sure how the image was set on that position.
I have read somewhere that when the listView is scrolled, the view is refreshed. Is that causing the problem?
Can anyone help how can iresolve this? I want the image to be shown(loaded) on the listView item on which i clicked and now other listView item.
Below is the xml stating listView items
method_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/white"
android:text="This is a check box button which reacts upon the check that user clicks. I am testing it with the big string and checking how it looks" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignParentRight="true"
android:layout_marginRight="34dp" />
</RelativeLayout>
Below is the part of class snippet:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.method_list_main);
final ListView list = (ListView)findViewById(R.id.listView1);
adapter=new MethodLazyAdapter(this,ARRAY.preparationSteps,ARRAY.timeToPrepare,ARRAY.arrowValue,noOfSteps,list);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
RelativeLayout ll = (RelativeLayout) view;
ImageView image = (ImageView)ll.findViewById(R.id.imageView2);
if(tick[position]){
tick[position] = false;
image.setImageResource(0);
}
else{
tick[position] = true;
image.setImageResource(R.drawable.select_right);
}
System.out.println("Position is: "+position);
}
});
}
Initially all tick[i] value is set to false.
Below is the getView function of adapter class
public View getView(final int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.method_item, null);
TextView text = (TextView)vi.findViewById(R.id.textView1);
text.setText(preparationSteps\[position\]);
return vi;
}
Try this to get what you want
in public area add this variable
public SparseBooleanArray checked = new SparseBooleanArray();
then in onItemClick
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
boolean stat = checked.get(position, false);
checked.put(position, !stat);
adapter.setChecked();
System.out.println("Position is: "+position);
}
});
and in Adapter Class
If adapter not sub class in activiy add variable in public area
private SparseBooleanArray checked = new SparseBooleanArray();
and add this method to class
public void setChecked(SparseBooleanArray ch){
checked = ch;
notifyDataSetChanged();
}
Or if it sub class use our cheked variable we defined it up
then in getView method
public View getView(final int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.method_item, null);
TextView text = (TextView)vi.findViewById(R.id.textView1);
text.setText(preparationSteps\[position\]);
ImageView image = (ImageView)vi.findViewById(R.id.imageView2);
if(checked.get(position, false)){
image.setImageResource(0);
}
else{
image.setImageResource(R.drawable.select_right);
}
return vi;
}
Please let me know if this help you.
Check out this post:
android - populating ListView with data from JSONArray
the reason for that is bacouse your are using your converted view wrong.
follow the example code on the post i paste.
if you will inflate your row view every time this problem will disappear. but this implementation is not recommended.

Android: button showing up multiple times in list view

I trying to write code to highlight the selected value of the list with "Next" button at the bottom of the layout. But for some reason, after every list item, "next" button also shows up. Can someone please help me resolve this problem?
Here is the layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/questionLayout"
>
<TextView android:id="#+id/txtExample"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textColor="#000000"
android:background="#FF0000"
/>
<ListView
android:id="#+id/listExample"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#CCCCCC"
android:choiceMode="singleChoice"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<Button
android:id = "#+id/next"
android:text="Next"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity="center"
android:layout_weight="50"
/>
<Button
android:id = "#+id/submit"
android:text="Submit"
android:layout_width = "0dp"
android:layout_height = "wrap_content"
android:layout_weight="50"
android:layout_gravity="center"
/>
</LinearLayout>
</LinearLayout>
Java Code:
public class updateList extends Activity {
private SelectedAdapter selectedAdapter;
private ArrayList<String> list;
int correct_answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<String>();
list.add("Choice One");
list.add("Choice Two");
list.add("Choice Three");
selectedAdapter = new SelectedAdapter(this,0,list);
selectedAdapter.setNotifyOnChange(true);
ListView listview = (ListView) findViewById(R.id.listExample);
listview.setAdapter(selectedAdapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
// user clicked a list item, make it "selected"
selectedAdapter.setSelectedPosition(position);
}
});
}
}
Thanks in advance
SSP
Selected Adaptor class:
public class SelectedAdapter extends ArrayAdapter{
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public SelectedAdapter(Context context, int textViewResourceId,
List objects) {
super(context, textViewResourceId, objects);
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// only inflate the view if it's null
if (v == null) {
LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.activity_main, null);
}
// get text view
TextView label = (TextView)v.findViewById(R.id.txtExample);
// change the row color based on selected state
if(selectedPos == position){
label.setBackgroundColor(Color.CYAN);
}else{
label.setBackgroundColor(Color.WHITE);
}
label.setText(this.getItem(position).toString());
/*
// to use something other than .toString()
MyClass myobj = (MyClass)this.getItem(position);
label.setText(myobj.myReturnsString());
*/
return(v);
}
}
change your listview in xml as like this
<ListView
android:id="#+id/listExample"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"//===== set maximum heighthere
android:layout_marginBottom="50dp"// === give some space at bottom so that buttons will appear
android:background="#CCCCCC"
android:choiceMode="singleChoice"
/>
But for some reason, after every list item, "next" button also shows up.
The ListView's row layout is determined by the layout you inflate in getView() or pass to your Adapter's super class if you haven't overridden getView(). Double check this layout and remove the unwanted code.
Addition
The layout for your ListView's items only needs to be one TextView since you only want to display a phrase in each. However you are currently passing your entire main layout, this creates the Buttons, an unused ListView, and everthing else in every row...
Instead use android.R.layout.simple_list_item_1 in getView(), of course you'll need to change the id you pass to findViewById() as well:
if (v == null) {
LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(android.R.layout.simple_list_item_1, null);
}
// get text view
TextView label = (TextView)v.findViewById(android.R.id.text1);
Please watch Android's Romain Guy discuss writing an efficient adapter to speed things up.

Categories

Resources