I've searched a lot this but I really did not find what I need exactly.
What I want is :
I have a listview and load it on my main class. I load it like this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main.this,
R.layout.myrow,R.id.text );
if (friends != null) {
for (ParseObject friend : friends) {
adapter.add((String) friend.get("name"));
}
}
setListAdapter(adapter);
and myrow layout xml is here:
< RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<ProgressBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/my_prog"
></ProgressBar>
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="25sp" >
</TextView>
</RelativeLayout >
You can see I have progress bar on textview so I need to reach it and set it's visible. I mean sometimes I set it invisible sometimes visible
What I did is:
On my MainActivity on create method the code is here :
ProgressBar my_prog;
my_prog=(ProgressBar)findViewById(R.id.my_prog);
my_prog.setVisibility(View.INVISIBLE);
The error is:
07-16 13:35:39.219: E/AndroidRuntime(29096): java.lang.RuntimeException: Unable to start activity ComponentInfo{....MainActivity}: java.lang.NullPointerException
I think I cant reach my_prog on my main activity but I need it.
How can I do that.
thanks in adnvace...
You need to implement a custom Adapter to do this. I have written this ExampleAdapter to show you how it works, I commented all the important parts:
public class ExampleAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private final List<ParseObject> objects;
private final boolean[] activated;
public ExampleAdapter(Context context, List<ParseObject> objects) {
this.inflater = LayoutInflater.from(context);
this.objects = objects;
this.activated = new boolean[objects.size()];
}
public void showProgressBar(int position, boolean visible) {
this.activated[position] = visible;
notifyDataSetChanged();
}
#Override
public int getCount() {
return this.objects.size();
}
#Override
public ParseObject getItem(int position) {
return this.objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If the convertView is null, we need to inflate a new one
if(convertView == null) {
// We inflate the view with your layout
convertView = inflater.inflate(R.layout.myrow, parent, false);
// Here we create a view holder object which keeps a
// reference to the Views in this row so we have to
// perform the expensive findViewById() only once
ViewHolder holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.my_prog = (ProgressBar) convertView.findViewById(R.id.my_prog);
// The view holder is set as tag to the view so we can access it later
convertView.setTag(holder);
}
// We retrieve the ParseObject for the current position
ParseObject parseObject = getItem(position);
// And get the view holder from the View
ViewHolder holder = (ViewHolder) convertView.getTag();
// We read the data we need from the ParseObject
String name = parseObject.get("name");
// And here is the visibility logic
int progressBarVisibility = this.activated[position] ? View.VISIBLE : View.GONE;
int textViewVisibility = this.activated[position] ? View.GONE : View.VISIBLE;
// Now we set the data to the Views through the view holder
holder.text.setText(name);
holder.text.setVisibility(textViewVisibility);
holder.my_prog.setVisibility(progressBarVisibility);
return convertView;
}
// This is our view holder class. It keeps a reference to the Views
// inside each row so we have to perform the expensive
// findViewById() only once
private class ViewHolder {
public TextView text;
public ProgressBar my_prog;
}
}
You can use the ExampleAdapter like this:
if(friends != null) {
ExampleAdapter adapter = new ExampleAdapter(Main.this, friends);
setListAdapter(adapter);
}
If you want to show a ProgressBar at a specific position you just do this:
// Shows the ProgressBar in the first row
adapter.showProgressBar(0, true)
Related
I'm trying to implement button on each row in ListView, but I saw many topics and I don't succeeded to add code to mine. Here is my MainActivity :
public class MainActivity extends AppCompatActivity {
private ArrayAdapter<String> itemsAdapter;
private ArrayList<String> items;
private ImageButton formButton;
private ListView lvMain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
commonFunction();
}
public void commonFunction() {
lvMain = (ListView) findViewById(R.id.lvMain);
items = new ArrayList<String>();
readItems();
itemsAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
items);
lvMain.setAdapter(itemsAdapter);
formButton = (ImageButton) findViewById(R.id.btnPlus);
formButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setLayoutActivity();
}
});
}
}
Here is my activity_main.xml :
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lvMain"
android:layout_above="#+id/btnPlus" />
<ImageButton
android:layout_width="match_parent"
android:layout_height="65dp"
android:id="#+id/btnPlus"
android:layout_alignParentBottom="true"
app:srcCompat="#mipmap/ic_plus_foreground" />
Does someone any idea how to do ?
Create custom adapter with custom row layout file and add button on that row file and bind it to List/Recycler view. So it will inflate in all row.
Add below code in row_list.xml file.
<ImageButton
android:layout_width="match_parent"
android:layout_height="65dp"
android:id="#+id/btnPlus"
android:layout_alignParentBottom="true"
app:srcCompat="#mipmap/ic_plus_foreground" />
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
private ArrayList data;
private static LayoutInflater inflater = null;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(ArrayList d) {
/********** Take passed values **********/
data = d;
/*********** Layout inflater to call external xml layout () ***********/
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {
public ImageButton button;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.row_list, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.button = (ImageView) vi.findViewById(R.id.btnPlus);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Button click
}
});
return vi;
}}
Hope it will solve problem.
Happy coding!!
Crate custom adapter and bind it with the ListView.
Inflate custom layout for each row in the adapter.
You can put your button in the custom layout file.
public class CustomAdapter extends ArrayAdapter<String> {
private Context context;
private int singleRowLayoutId;
public CustomAdapter(Context context, int singleRowLayoutId, String []titles, String []desc, int []images ) {
super(context, singleRowLayoutId,titles);
this.context=context;
this.singleRowLayoutId=singleRowLayoutId; //custom row layout for list view item
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row=convertView;
CustomViewHolder holder=null;
if(row==null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//view object of single row of list view
row = inflater.inflate(singleRowLayoutId, parent, false);
//by using holder, we make sure that findViewById() is not called every time.
holder=new CustomViewHolder(row);
row.setTag(holder);
}
else
{
holder=(CustomViewHolder)row.getTag();
}
return row;
}
private class CustomViewHolder {
private ImageButton mbtn;
CustomViewHolder(View view)
{
mbtn=(ImageButton)view.findViewById(R.id.btn);
mbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle button click here
}
});
}
}
I think that this is what you need - create a separate layout for the rows in the list view. Then create a custom adapter, where you are adding this layout as row layout and then set this adapter to your list view. Here are the details with examples:
Android custom Row Item for ListView
So I have a listview with one textview and I want to add a second textview to it. But I cannot figure out how to modify the adapter and then call it in my main activity, even after looking through many similiar questions on stackoverflow.
Heres how my CustomAdapter.java is now
class CustomAdapter extends ArrayAdapter<CharSequence>{
public CustomAdapter(Context context, CharSequence[] routes) {
super(context, R.layout.custom_row ,routes);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater routeInflater = LayoutInflater.from(getContext());
View customView = convertView;
if(customView == null){customView = routeInflater.inflate(R.layout.custom_row, parent, false);}
CharSequence singleRoute = getItem(position);
TextView routeText = (TextView) customView.findViewById(R.id.routeText);
routeText.setText(singleRoute);
///// Textview I want to add
CharSequence routeNum = getItem(position);
TextView routeNumText = (TextView) customView.findViewById(R.id.numbersTextView);
routeNumText.setText(routeNum);
/////
return customView;
and heres my MainActivity.java
///// fill listview numbers I want to add
final String[] routeListviewNumbers = getResources().getStringArray(R.array.routeNumbers);
//fill list view with xml array of routes
final String[] routeListViewItems = getResources().getStringArray(R.array.routeList);
//custom adapter for list view
ListAdapter routeAdapter = new CustomAdapter(this, routeListViewItems);
final ListView routeListView = (ListView) findViewById(R.id.routeListView);
routeListView.setAdapter(routeAdapter);
any help in how to modify the adapter and then call it in the main activity would be really appreciated. Thank you!
I would recommend creating a custom Route class since this adapter is meant to handle one array. Create some member variables for the route number and route items in the new class with getter and setter methods. Then you should be able to create a new array list of Route objects in your main activity and iterate through the existing string arrays while appending them (as new Route objects) to the new array.
You will have to change the adapter to accept a Route object instead of CharSequence. Hope this points you in the right direction.
I would recommend a custom adapter for you.
Exm..
Create Route Class
class Route{
public int number;
public String text;
}
Base Adapter...
public class myBaseAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<Route> mRouteList;
public BilgiAdapter(Activity activity,List<Route> routeList){
mInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRouteList = routeList;
}
#Override
public int getCount() {
return mRouteList.size();
}
#Override
public Object getItem(int position) {
return mRouteList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View myView;
myView = mInflater.inflate(R.layout.line_layout,null);
Route r = mRouteList.get(position);
TextView txtRouteNumber = (TextView)myView.findViewById(R.id.textRouteNumber);
TextView txtRouteText = (TextView)myView.findViewById(R.id.textRouteText);
txtRouteNumber.setText(String.ValueOf(r.number));
txtRouteText.setText(String.ValueOf(r.text));
return myView;
}
}
MainActivity vs..
ListView lstRoute;
myBaseAdapter adapter;
List<Route> list;
...
..
..
..
..
OnCreate(..)
..
list = new ArrayList<Route>();
//add routes in list
myBaseAdapter = new myBaseAdapter(MainActivity.this,list);
lstRoute = (ListView)findViewById(R.id.listViewRoute);
lstRoute.setAdapter(myBaseAdapter);
...
..
..
line_layout.xml(Layout 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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textRouteNumber"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textRouteText"/>
</LinearLayout>
I'm basically trying to display multiple views via the same ListView adapter. However, the adapter ends up generating multiple duplicates and crashes sometimes as well with a NullPointer. My guess is that I have implemented the adapter all wrong. Here's my complete code:
The item could either be a photo or a text.
Adapter:
public class FeedAdapter extends BaseAdapter {
static private Activity activity;
private static LayoutInflater inflater = null;
ArrayList<ActivityTable> actList = new ArrayList<ActivityTable>();
Holder holder;
public FeedAdapter(Activity a, ArrayList<ActivityTable> actList) {
activity = a;
this.actList = actList;
}
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
final ActivityTable act = actList.get(position);
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
if (act.getType().equals("text")) {
convertView = inflater.inflate(R.layout.feed_single_text, null);
holder = new Holder();
//More code that Set the caption to the holder
convertView.setTag(holder);
}
if (act.getType().equals("photo")) {
convertView = inflater.inflate(R.layout.feed_single_picture, parent, false);
holder = new Holder();
holder.media = (ImageView) convertView.findViewById(R.id.postphoto);
//More code that Set the photo to the holder
convertView.setTag(holder);
}
} else {
holder = (Holder) convertView.getTag();
}
return convertView;
}
public static class Holder {
ImageView media;
TextView caption;
}
}
Am I inflating multiple views in the same adapter the wrong way? Can anyone point out the error?
You have 2 diffrent layout for each row so I think you should add
#Override
public int getViewTypeCount() {
return 2;
}
to your listview adapter
In your code, try to initial your LayoutInflater inside the constructor of your adapter
public FeedAdapter(Activity a, ArrayList<ActivityTable> actList) {
...
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
And also you should optimize your ListView performance
Here is my experience
It is good to have these 3 in place.
#Override
public int getCount() {
return actList().size();
}
#Override
public Object getItem(int position) {
return actList().get(position);
}
#Override
public long getItemId(int position) {
return position;
}
Here is the important part,
first you have to tell the adapter how many type,
and then you have to tell the adapter how to determine the type.
Here I tell type View Type = 2
#Override
public int getViewTypeCount() {
return 2;
}
and Here I tell the adapter How I put the type number into the array
I use setType = 0 || set Type = 1
personal preference here: I like to use int instead of String
#Override
public int getItemViewType(int position) {
return act.get(position).getType();
}
and then later at the getView
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
int listViewItemType = getItemViewType(position);
if (v == null) {
..whatevever you doing to make v not null
}
if (listViewItemType == 0) {
//Do something
}else if(listViewItemType == 1){
// Do something different
}
return v;
}
Yes you will get duplicate Item, Because Convertview is reusing. Once convertview is created that view using if you scroll.
So better use single layout and with both Image and text. Based type hide any one.
xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/ImgFeed"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txtCaption"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
try this you are using ImageView insted of TextView
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
final ActivityTable act = actList.get(position);
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.feed_layout, null);
holder = new Holder();
holder.caption = (TextView) convertView.findViewById(R.id.txtCaption);
holder.media = (ImageView) convertView.findViewById(R.id.ImgFeed);
if (act.getType().equals("text")) {
holder.media.setVisibility(View.GONE)
}
else if (act.getType().equals("photo")) {
holder.caption.setVisibility(View.GONE)
}
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
return convertView;
}
I'm trying to make a task manager, and I only have one problem. I have a listview that gets inflated. All the elements in the listview are correct. The problem is that when I select an item, the listview will select another item away. I've heard listviews repopulate the list as it scrolls down to save memory. I think this may be some sort of problem. Here is a picture of the problem.
If i had more apps loaded, then it would continue to select multiple at once.
Here is the code of my adapter and activity and XML associated
public class TaskAdapter extends BaseAdapter{
private Context mContext;
private List<TaskInfo> mListAppInfo;
private PackageManager mPack;
public TaskAdapter(Context c, List<TaskInfo> list, PackageManager pack) {
mContext = c;
mListAppInfo = list;
mPack = pack;
}
#Override
public int getCount() {
return mListAppInfo.size();
}
#Override
public Object getItem(int position) {
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
//System.out.println("Setting LayoutInflater in TaskAdapter " +mContext +" " +R.layout.taskinfo +" " +R.id.tmbox);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
final CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
if(v.isSelected())
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
}
else
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
}
}
});
return convertView;
public class TaskManager extends Activity implements Runnable
{
private ProgressDialog pd;
private TextView ram;
private String s;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.taskpage);
setTitleColor(Color.YELLOW);
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run()
{
//System.out.println("In Taskmanager Run() Thread");
final PackageManager pm = getPackageManager();
final ListView box = (ListView) findViewById(R.id.cBoxSpace);
final List<TaskInfo> CK = populate(box, pm);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
ram.setText(s);
box.setAdapter(new TaskAdapter(TaskManager.this, CK, pm));
//System.out.println("In Taskmanager runnable Run()");
endChecked(CK);
}
});
handler.sendEmptyMessage(0);
}
Taskinfo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/tmImage"
android:layout_width="48dp"
android:layout_height="48dp"
android:scaleType="centerCrop"
android:adjustViewBounds="false"
android:focusable="false" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tmbox"
android:lines="2"/>
</LinearLayout>
Taskpage.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#+id/cBoxSpace"
android:layout_width="wrap_content"
android:layout_height="400dp"
android:orientation="vertical"/>
<TextView
android:id="#+id/RAM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp" />
<Button
android:id="#+id/endButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="End Selected Tasks" />
</LinearLayout>
Any ideas for what reason mutliple items are selected with a single click would be GREATLY appreciated. I've been messing around with different implementations and listeners and listadapters but to no avail.
I think the point is you only save checking state in the view(v.setSelected).
And you reuse these view, so its checkbox is always not change its state.
You can create a state array to save every checking state of every TaskInfo, and check this array when you create a view.
for example
// default is false
ArrayList<Boolean> checkingStates = new ArrayList<Boolean>(mListAppInfo.size());
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
final CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
checkBox.setChecked(checkingStates.get(position));
convertView.setSelected(checkingStates.get(position));
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(v.isSelected())
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
checkingStates.get(position) = false;
}
else
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
checkingStates.get(position) = true;
}
}
});
return convertView;
}
I'm not 100% sure what you are trying to do, but part of your problem might be related to the condition in your onClick method:
if(v.isSelected())
I think you want that to read
if(v.isChecked())
isSelected is inherited from View, and it means something different from isChecked
Also, the whether the CheckBox is checked or not is independent from your data model since it is a recycled view. Your CheckBox should be checked based on entry (I'm assuming your TextInfo class has an isChecked() method that returns a boolean:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
//System.out.println("Setting LayoutInflater in TaskAdapter " +mContext +" " +R.layout.taskinfo +" " +R.id.tmbox);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
checkBox.setChecked(entry.isChecked());
}
I don't think you need the View.OnClickListener you are attaching to convertView. You should handle that in the OnItemClickListener attached to the ListView. Assuming your ListView is called listView and TaskInfo instances have setChecked and isChecked methods:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
entry = mListAppInfo.get(position);
entry.setChecked(!entry.isChecked());
}
});
First of all don't set the list checked or unchecked on view position.
because view position means only visible items position in your listview but you would like to set checked or uncheked status on a particular list item.
That's why this problem arises in your code.
You have the need to set the items checked and unchecked on your custom arraylist getter setter like the code i have attached below:
package com.app.adapter;
public class CategoryDynamicAdapter {
public static ArrayList<CategoryBean> categoryList = new ArrayList<CategoryBean>();
Context context;
Typeface typeface;
public static String videoUrl = "" ;
Handler handler;
Runnable runnable;
// constructor
public CategoryDynamicAdapter(Activity a, Context context, Bitmap [] imagelist,ArrayList<CategoryBean> list) {
this.context = context;
this.categoryList = list;
this.a = a;
}
// Baseadapter to the set the data response from web service into listview.
public BaseAdapter mEventAdapter = new BaseAdapter() {
#Override
public int getCount() {
return categoryList.size();
}
#Override
public Object getItem(int position) {
return categoryList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
class ViewHolder {
TextView title,category,uploadedBy;
ImageView image;
RatingBar video_rating;
Button report_video ,Flag_video;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder vh = null ;
if(convertView == null) {
vh = new ViewHolder();
convertView = LayoutInflater.from(context).inflate (R .layout.custom_category_list_layout,null,false);
vh.title = (TextView) convertView .findViewById (R.id.title);
vh.image = (ImageView) convertView.findViewById(R.id.Imagefield);
convertView.setTag(vh);
}
else
{
vh=(ViewHolder) convertView.getTag();
}
try
{
final CategoryBean Cb = categoryList.get(position);
//pay attention to code below this line i have shown here how to select a listview using arraylist getter setter objects
String checkedStatus = Cb.getCheckedStringStaus();
if(checkdStatus.equal("0")
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
}
else ////checkdStatus.equal("1")
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
}
catch (Exception e)
{
e.printStackTrace();
}
I have a problem with changing the background of a view in a ListView.
What I need:
Change the background image of a row onClick()
What actually happens:
The background gets changed (selected) after pressing e.g. the first entry. But after scrolling down the 8th entry is selected too.
Scroll back to the top the first isn't selected anymore. The second entry is selected now.
Continue scrolling and it continues jumping...
What i'm dong in the Code:
I have channels, and onClick() I toggle an attribute of channel boolean selected
and then I change the background.
I'm doing this only onClick() thats why I don't get why it's actuelly happening on other entries too.
One thing I notices is: It seems to be only the "drawing"-part because the item which get selected "by it self" has still the selected value on false
I think it seems to have something to do with the reuse of the views in the custom ListAdapters getView(...)
Code of onClick() in ListActivity:
#Override
protected ViewHolder createHolder(View v) {
// createHolder will be called only as long, as the ListView is not
// filled
TextView title = (TextView) v
.findViewById(R.id.tv_title_channel_list_adapter);
TextView content = (TextView) v
.findViewById(R.id.tv_content_channel_list_adapter);
ImageView icon = (ImageView) v
.findViewById(R.id.icon_channel_list_adapter);
if (title == null || content == null || icon == null) {
Log.e("ERROR on findViewById",
"Couldn't find Title, Content or Icon");
}
ViewHolder mvh = new MyViewHolder(title, content, icon);
// We make the views become clickable
// so, it is not necessary to use the android:clickable attribute in
// XML
v.setOnClickListener(new ChannelListAdapter.OnClickListener(mvh) {
public void onClick(View v, ViewHolder viewHolder) {
// we toggle the enabled state and also switch the the
// background
MyViewHolder mvh = (MyViewHolder) viewHolder;
Channel ch = (Channel) mvh.data;
ch.setSelected(!ch.getSelected()); // toggle
if (ch.getSelected()) {
v.setBackgroundResource(R.drawable.row_blue_selected);
} else {
v.setBackgroundResource(R.drawable.row_blue);
}
// TESTING
Log.d("onClick() Channel", "onClick() Channel: "
+ ch.getTitle() + " selected: " + ch.getSelected());
}
});
return mvh;
}
Code of getView(...):
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
// When view is not null, we can reuse it directly, there is no need
// to reinflate it.
// We only inflate a new View when the view supplied by ListView is
// null.
if (view == null) {
view = mInflater.inflate(mViewId, null);
// call own implementation
holder = createHolder(view);
// TEST
// we set the holder as tag
view.setTag(holder);
} else {
// get holder back...much faster than inflate
holder = (ViewHolder) view.getTag();
}
// we must update the object's reference
holder.data = getItem(position);
// <EDIT SOLUTION>
if(getItem(position).get_id() == channelList.get(position).get_id()){
if(getItem(position).getSelected())
{
view.setBackgroundResource(R.drawable.row_blue_selected);
}
else{
view.setBackgroundResource(R.drawable.row_blue);
}
}
// </EDIT SOLUTION>
// call the own implementation
bindHolder(holder);
return view;
}
I really would appreciate any idea how to solve this! :)
If more information is needed please tell me.
Thanks in advance!
Let me show you the code that I use for every ListView and properly controlling the click event for changing the background and doing anything further
public class Offices extends Activity {
private ListView listView;
/* selectedListItem will contain the number of items to be selected.
* Your list item OnOlickListener will simply change this variable
* to the position of the clicked item. The Adapter will do the rest
* because you need to refresh the ListView.
*/
private int selectedListItem = -1;
private Handler mHandler = new Handler();
private Vector<String> data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.officeslayout);
data = new Vector<String>();
// Add data as per your requirement
data.add("one");
data.add("two");
data.add("three");
data.add("four");
data.add("Five");
data.add("Six");
data.add("Seven");
data.add("Eight");
data.add("Nine");
data.add("Ten");
listView = (ListView)findViewById(R.id.ListView01);
listView.setDivider(null);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectedListItem = position;
((EfficientAdapter)listView.getAdapter()).notifyDataSetChanged();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
// call any new activity here or do any thing you want here
}
}, 200L);
}
});
listView.setAdapter(new EfficientAdapter(getApplicationContext()));
}
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null || convertView.getTag() == null) {
convertView = mInflater.inflate(R.layout.officeslistitemlayout, null);
holder = new ViewHolder();
holder.backgroundView = (ImageView) convertView
.findViewById(R.id.OfficesBackground);
holder.officesTitle = (TextView) convertView
.findViewById(R.id.OfficesName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(position == selectedListItem) {
holder.backgroundView.setBackgroundResource(R.drawable.and_gray_bg_listing_selected);
} else {
holder.backgroundView.setBackgroundResource(R.drawable.and_gray_bg_listing);
}
holder.officesTitle.setText(data.get(position));
return convertView;
}
}
static class ViewHolder {
TextView officesTitle;
ImageView backgroundView;
}
}
officeslistitemlayout.xml file will be like following add drawable and design it according to you put the following code in RelativeLayout
<ImageView android:id="#+id/OfficesBackground" android:layout_width="fill_parent"
android:layout_height="45dip"
android:layout_alignParentTop="true"
android:background="#drawable/and_gray_bg_listing"
android:scaleType="fitXY"
></ImageView>
<TextView android:id="#+id/OfficesName" android:layout_width="wrap_content"
android:text="Offices Name"
android:textColor="#000000" android:textStyle="bold"
android:layout_height="wrap_content"
android:layout_centerVertical="true" android:layout_marginLeft="5dip"
></TextView>
Hope it will help :)