This question already exists:
OnListItemClick event is not working
Closed 8 years ago.
I have been facing a problem...there is a five different Java classes MainActivity, Application, ApplicationAdapter, FetchData ,FetchDataListener.. I am binding mysql data from api in ListView... but I am trying to fire a click event on ListView but I am getting error....here is code...
MainActivity.java
#Override
public void onFetchComplete(List<Applicity> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
public void onListItemClick(ListView l, View v, int position, long id) {
Applicity app= new Applicity();
int p =app.getPosition(position);
Toast.makeText(this,p,Toast.LENGTH_LONG).show();
}
ApplicationAdapter.java
public class ApplicationAdapter extends ArrayAdapter<Applicity>{
private List<Applicity> items;
public ApplicationAdapter(Context context, List<Applicity> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
}
Applicity app = items.get(position);
if(app != null) {
ImageView icon = (ImageView)v.findViewById(R.id.appIcon);
TextView titleText = (TextView)v.findViewById(R.id.titleTxt);
LinearLayout ratingCntr = (LinearLayout)v.findViewById(R.id.ratingCntr);
TextView dlText = (TextView)v.findViewById(R.id.dlTxt);
if(icon != null) {
Resources res = getContext().getResources();
String sIcon = "com.sj.jsondemo:drawable/" + app.getIcon();
icon.setImageDrawable(res.getDrawable(res.getIdentifier(sIcon, null, null)));
}
if(titleText != null) titleText.setText(app.getTitle());
if(dlText != null) {
NumberFormat nf = NumberFormat.getNumberInstance();
dlText.setText(nf.format(app.getTotalDl())+" dl");
}
if(ratingCntr != null && ratingCntr.getChildCount() == 0) {
/*
* max rating: 5
*/
for(int i=1; i<=5; i++) {
ImageView iv = new ImageView(getContext());
if(i <= app.getRating()) {
iv.setImageDrawable(getContext().getResources().getDrawable(R.drawable.start_checked));
}
else {
iv.setImageDrawable(getContext().getResources().getDrawable(R.drawable.start_unchecked));
}
ratingCntr.addView(iv);
}
}
}
return v;
}
}
Applicity.java
public class Applicity {
private String title;
private long totalDl;
private int rating;
public int position;
private String icon;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getTotalDl() {
return totalDl;
}
public void setTotalDl(long totalDl) {
this.totalDl = totalDl;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public int getPosition(int arg){
return position;
}
}
Use OnItemClickListener. You're creating a new custom method instead of OnItemClickListener.
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Do something here.
}
});
Related
In my App, I'm using Custom Listview, where I need to delete an item from Listview as well as corresponding row from CSV file simultaneously when Listview is long clicked.
My CSV file looks like this
2020/11/22,10:30PM,96.3°F,Normal,Body
2020/11/22,10:30PM,98.2°F,Normal,Body
2020/11/22,10:31PM,96.7°F,Normal,Body
2020/11/22,10:40PM,95.0°F,Normal,Body
For instance, if second item from Listview is removed when long clicked, the corresponding data row from CSV file above which is second row on CSV file should also be removed when Listview is long clicked.
Here's my Code:
LogViewActivity.java
public class LogViewActivity extends BaseAppCompatActivity {
private static final String TAG = "LogViewActivity";
private File logFile;
private Toolbar toolbar;
private ListView lvproducts;
ArrayList<Product> list;
ProductAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.log_view_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
public void onResume() {
super.onResume();
logFile = (File) getIntent().getExtras().get(Constants.EXTRA_LOG_FILE);
if (logFile != null) {
toolbar.setTitle(logFile.getName());
try {
setLogText(logFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_log_view, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.action_send_to:
intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(logFile), "text/plain");
startActivity(intent);
break;
default:
Log.e(TAG, "Unknown id");
break;
}
return super.onOptionsItemSelected(item);
}
private void setLogText(File file) throws FileNotFoundException {
// Textview visisbility is invisible and used only for setting up String data.
TextView textView1 = (TextView) findViewById(R.id.tvview1);
TextView textView2 = (TextView) findViewById(R.id.tvview2);
TextView textView3 = (TextView) findViewById(R.id.tvview3);
TextView textView4 = (TextView) findViewById(R.id.tvview4);
TextView textView5 = (TextView) findViewById(R.id.tvview5);
lvproducts = (ListView) findViewById(R.id.lvproducts);
list =new ArrayList<Product>();
Scanner inputStream;
inputStream = new Scanner(file);
while(inputStream.hasNext()){
String line= inputStream.next();
if (line.equals("")) { continue; } // <--- notice this line
String[] values = line.split(",");
String V = values[0];
String W= values[1];
String X= values[2];
String Y= values[3];
String Z= values[4];
// Textview visisbility is invisible and used only for setting up String data.
textView1.setText(Z);
textView2.setText(X);
textView3.setText(Y);
textView4.setText(V);
textView5.setText(W);
Product product1 = new Product(textView1.getText().toString(), textView2.getText().toString(), textView3.getText().toString(), textView4.getText().toString(), textView5.getText().toString());
list.add(product1);
adapter = new ProductAdapter(LogViewActivity.this, list);
lvproducts.setAdapter(adapter);
}
inputStream.close();
lvproducts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int which_item = position;
new AlertDialog.Builder(LogViewActivity.this)
.setTitle(getResources().getString(R.string.delete_log_file_title))
.setMessage(getResources().getString(R.string.delete_log_file_text) + "\n"
+ getResources().getString(R.string.file_name))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
list.remove(which_item);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
return true;
}
});
}
}
Product.java
public class Product {
private String mode;
private String temp;
private String condition;
private String dates;
private String times;
public Product(String mode, String temp, String condition, String dates, String times) {
this.mode = mode;
this.temp = temp;
this.condition = condition;
this.dates = dates;
this.times = times;
}
public String getMode() {
return mode;
}
public String getTemp() {
return temp;
}
public String getCondition() {
return condition;
}
public String getDates() {
return dates;
}
public String getTimes() {
return times;
}
}
ProductAdapter.java
public class ProductAdapter extends ArrayAdapter<Product> {
private final Context context;
private final ArrayList<Product> values;
public ProductAdapter(#NonNull Context context, ArrayList<Product> list) {
super(context, R.layout.row_layout, list);
this.context = context;
this.values = list;
}
#SuppressLint("ResourceAsColor")
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowview = inflater.inflate(R.layout.row_layout, parent, false);
CardView cdview = (CardView) rowview.findViewById(R.id.cdview);
TextView tvtemp = (TextView) rowview.findViewById(R.id.tvtemp);
TextView tvcondition = (TextView) rowview.findViewById(R.id.tvcondition);
TextView tvdate = (TextView) rowview.findViewById(R.id.tvdate);
TextView tvtime = (TextView) rowview.findViewById(R.id.tvtime);
ImageView ivmode = (ImageView) rowview.findViewById(R.id.ivmode);
tvtemp.setText(values.get(position).getTemp());
tvcondition.setText(values.get(position).getCondition());
tvdate.setText(values.get(position).getDates());
tvtime.setText(values.get(position).getTimes());
if(values.get(position).getMode().equals("Object") && (values.get(position).getCondition().equals("None")) && (!values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_blue);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.homewhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("Normal")) && (!values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backgreen);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("Low-Grade-Fever")) && (!values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backyellow);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("High-Fever")) && (!values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backred);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("HIGH")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backred);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("LOW")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_low);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_black);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Object") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_black);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.homewhite);
}
return rowview;
}
}
Please help me out. Thank you!
You are only removing item from the loaded data set, therefore only list item is removing. You need to update your csv file on removal of list item
lvproducts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int which_item = position;
new AlertDialog.Builder(LogViewActivity.this)
.setTitle(getResources().getString(R.string.delete_log_file_title))
.setMessage(getResources().getString(R.string.delete_log_file_text) + "\n"
+ getResources().getString(R.string.file_name))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
list.remove(which_item);
adapter.notifyDataSetChanged();
updateCSVFile();
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
return true;
}
});
public void updateCSVFile() {
// Write your logic her to update CSV file after item removal.
}
I am trying to make an application with a ListView that include a Country Flag and name. This is so that the user can click on them and be shown images of the country that they wouldve taken before. However for about 3 seconds when the listview loads if i try to scroll it will sort of glitch and send me back to top. This is the code..
public class CountriesListAdapter extends ArrayAdapter {
private int resource;
private LayoutInflater inflater;
private List<CountryModel> countryModels;
private WeakReference<TextView> selectedCountryIdtxt;
private boolean useFilter;
private WeakReference<ProgressBar> progressBarWeakReference;
public int getSelectedCountryId() {
return selectedCountryId;
}
public void setSelectedCountryId(int selectedCountryId) {
this.selectedCountryId = selectedCountryId;
}
private int selectedCountryId;
public CountriesListAdapter(#NonNull WeakReference<Context> context, int resourceId, WeakReference<TextView> textView, #NonNull List<CountryModel> countryModelList, boolean useFilter, WeakReference<ProgressBar> progressBarWeakReference){
super(context.get(), resourceId, countryModelList);
selectedCountryIdtxt = textView;
resource = resourceId; //the id of the template file
inflater = LayoutInflater.from(context.get());
this.countryModels = countryModelList;
selectedCountryId = -1;
this.useFilter = useFilter;
this.progressBarWeakReference = progressBarWeakReference;
}
public int getCount() {
if (countryModels != null)
return countryModels.size();
return 0;
}
public CountryModel getItem(int position) {
if (countryModels != null)
return countryModels.get(position);
return null;
}
public long getItemId(int position) {
if (countryModels != null)
return countryModels.get(position).hashCode();
return 0;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
// this method is automatically called for every object in our list
//basically it's called for every single row before it is generated
// this method is called per row
convertView = (ConstraintLayout) inflater.inflate(resource, null);
//the variable countryModel is fiiled with current object that is being processed
final CountryModel countryModel = countryModels.get(position);
TextView countryName = convertView.findViewById(R.id.countryNamelbl);
final ImageView countryFlag = convertView.findViewById(R.id.countryFlagimg);
final ImageView checked = convertView.findViewById(R.id.countryCheckedimg);
//this is done for every object in the list
assert countryModel != null;
countryName.setText(countryModel.getName());
Picasso.get().load(countryModel.getImage()).fit().into(countryFlag);
if(!useFilter) {
if (selectedCountryId == countryModel.getId()) {
checked.setVisibility(View.VISIBLE);
} else {
checked.setVisibility(View.INVISIBLE);
}
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!useFilter) {
if (checked.getVisibility() == View.VISIBLE) {
checked.setVisibility(View.INVISIBLE);
selectedCountryId = -1;
selectedCountryIdtxt.get().setText(String.valueOf(selectedCountryId));
} else {
if (selectedCountryId == -1) {
checked.setVisibility(View.VISIBLE);
selectedCountryId = countryModel.getId();
} else {
selectedCountryId = countryModel.getId();
notifyDataSetChanged();
}
selectedCountryIdtxt.get().setText(String.valueOf(selectedCountryId));
}
} else {
Intent i = new Intent(getContext(), PicturesActivity.class);
i.putExtra("countryId",countryModel.getId());
i.putExtra("countryName", countryModel.getName());
getContext().startActivity(i);
}
}
});
progressBarWeakReference.get().setVisibility(View.INVISIBLE);
return convertView;
}
public List<CountryModel> getCountryModels() {
return countryModels;
}
public void setCountryModels(List<CountryModel> countryModels) {
this.countryModels = countryModels;
}
}
The problem was actually in another class, i was calling the adapter for every list item instead of just once... oops.
Thanks for the replies though!
I have a listview which is showing some images. To avoid UI blocks, I tried to lazy load the thumbnails with an asyncTask in my adapter since that seemed the best solution I found here on SO.
This listView has also an onItemclick and an onItemLongClick listeners.
For some reason, my app is getting really slow down, expecially after performing an onlongclick action. The only thing I found unusual is that my ListView is calling the getView method in loop, never stopping.
Some code:
Adapter
public class FotoGridAdapter extends ArrayAdapter {
private Context context;
private int layoutResourceId;
private ArrayList<WorkorderPicture> workorderPictures = new ArrayList<WorkorderPicture>();
public FotoGridAdapter(Context context, int layoutResourceId, List<WorkorderPicture> pictures) {
super(context, layoutResourceId, pictures);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.workorderPictures = new ArrayList<>(pictures);
}
#Override
#Nullable
public WorkorderPicture getItem(int position) {
return workorderPictures.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = row.findViewById(R.id.text);
holder.image = row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
WorkorderPicture workorderPicture = workorderPictures.get(position);
if (workorderPicture != null) {
String text = workorderPicture.getTITLE();
if (workorderPicture.getPHOTODATE() != null) {
text += " - ";
text += new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(workorderPicture.getPHOTODATE());
}
holder.imageTitle.setText(text);
String format = AttachmentUtils.getExtensionFromFileName(workorderPicture.getFILE_NAME_WITH_EXTENSION());
if (format == null)
format = "default";
switch (format.toLowerCase()) {
case "image/jpeg":
case "image/png":
if (workorderPicture.getPHOTOSTREAM() != null) {
new ImageGridHandler(context, holder.image, workorderPicture.getPHOTOSTREAM(), workorderPicture.getPHOTOSTREAM().length).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// holder.image.setImageBitmap(sbm);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.image.setImageDrawable(getContext().getDrawable(R.drawable.ic_image));
} else {
holder.image.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_image));
}
}
break;
case "application/pdf":
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.image.setImageDrawable(getContext().getDrawable(R.drawable.ic_pdf));
} else {
holder.image.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_pdf));
}
break;
default:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.image.setImageDrawable(getContext().getDrawable(R.drawable.ic_empty_image));
} else {
holder.image.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_empty_image));
}
break;
}
}
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
class ImageGridHandler extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private Context context;
private byte[] photoStream;
private int length;
public ImageGridHandler(Context context, ImageView img, byte[] photoStream, int length) {
imageViewReference = new WeakReference<>(img);
this.context = context;
this.photoStream = photoStream;
this.length = length;
}
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bm = BitmapFactory.decodeByteArray(photoStream, 0, length);
return ThumbnailUtils.extractThumbnail(bm, 80, 100);
}
#Override
protected void onPostExecute(Bitmap result) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(result);
FotoGridAdapter.this.notifyDataSetChanged();
}
this.cancel(true);
}
}
}
Listeners
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view,
final int position, long l) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.myAlertDialogTheme)
.setNegativeButton("Annulla", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.setPositiveButton("Elimina", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final String wpID = openedIntervention.getWorkorderPictures().get(position).getID();
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.where(WorkorderPicture.class).equalTo("ID", wpID).findFirst().setDELETED(true);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
openedIntervention.setWorkorderPictures(realm.where(WorkorderPicture.class)
.equalTo("WORKORDER_ID", openedIntervention.getWorkorder()
.getID())
.equalTo("DELETED", false)
.findAll());
loadData();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
}
});
}
}).setTitle(app_name)
.setMessage("Eliminare l'allegato selezionato?");
builder.show();
return true;
}
});
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position,
long id) {
//code to show a preview
}});
Another info might be that I use Realm, but my pictures are unlinked from it, so I don't think it matter
AsyncTask is asynchronous and after every completion of task, your are notifying the adapter which is causing the data change event so
#Override
protected void onPostExecute(Bitmap result) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(result);
// FotoGridAdapter.this.notifyDataSetChanged();
// ^^^^^^^^^^^^^^^^ remove this
// not required in case of change in imageview
}
this.cancel(true);
}
I am trying to develop an activity where there is a custom listView made out of CustomAdapter.
The list consists of a TextView and an EditText. The EditText when clicked, it auto fetches the system time.
What I want is when a particular EditText is filled, I want all the previous(above) list items in the sequence to be disabled.
So far, I have tried using isEnabled() and areAllItemsEnabled() functions returning respective boolean values using position, but however didn’t work.
Please help me achieve the above.
Thanks.
This is my CustomAdapter Class
public class SelectStnListByRoute extends BaseAdapter implements View.OnClickListener {
Context context;
ArrayList<StnNames> stnList;
LayoutInflater layoutInflater = null;
ViewHolder viewHolder;
private int mLastClicked;
public SelectStnListByRoute(Context context, ArrayList<StnNames> stnList) {
super();
this.context = context;
this.stnList = stnList;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return stnList.size();
}
#Override
public Object getItem(int position) {
return stnList.get(position);
}
#Override
public long getItemId(int position) {
return stnList.indexOf(getItem(position));
}
public int getViewTypeCount() {
return 1;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
if(position==position){
return false;
}
return false;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int type = getItemViewType(position);
StnNames stnDetails = stnList.get(position);
viewHolder = new ViewHolder();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.footplate_custome_layout, null);
viewHolder.txtStnNAme = (TextView) convertView.findViewById(R.id.txtStnCode);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
viewHolder.txtStnDep = (TextView) convertView.findViewById(R.id.txtDepTime);
convertView.setTag(viewHolder);
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
} else {
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
}
viewHolder.txtStnNAme.setText(stnDetails.getStnCode());
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: " , String.valueOf(position)); //Here I am getting the position of the row item clicked, where should I put the Onclick false for disabling all of the above fields using the position?
}
});
viewHolder.txtStnDep.setOnClickListener(this);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
if (stnDetails.getArrivalTime() != null) {
viewHolder.txtStnArr.setText(stnDetails.getArrivalTime());
} else {
viewHolder.txtStnArr.setText("");
}
if (stnDetails.getDeptTime() != null) {
viewHolder.txtStnDep.setText(stnDetails.getDeptTime());
} else {
viewHolder.txtStnDep.setText("");
}
return convertView;
}
class ViewHolder {
TextView txtStnNAme, txtStnArr, txtStnDep;
int ref;
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case txtArrivalTime:
TextView textViewArrVal = (TextView) view.findViewById(R.id.txtArrivalTime);
textViewArrVal.setClickable(false);
StnNames listItemsArrr = (StnNames) textViewArrVal.getTag();
if (listItemsArrr.getArrivalTime() != getCurrentTime()) {
listItemsArrr.setArrivalTime(getCurrentTime());
if (listItemsArrr.getArrivalTime() != null) {
int position = textViewArrVal.getSelectionStart();
textViewArrVal.setText(listItemsArrr.getArrivalTime());
} else {
textViewArrVal.setText("");
}
}
break;
case txtDepTime:
TextView textViewDepVal = (TextView) view.findViewById(R.id.txtDepTime);
StnNames listItemsDepp = (StnNames) textViewDepVal.getTag();
if (listItemsDepp.getDeptTime() != getCurrentTime()) {
listItemsDepp.setDeptTime(getCurrentTime());
if (listItemsDepp.getDeptTime() != null) {
textViewDepVal.setText(listItemsDepp.getDeptTime());
} else {
textViewDepVal.setText("");
}
}
break;
default:
break;
}
}
public String getCurrentTime(){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String arrDate = mdformat.format(calendar.getTime());
return arrDate;
}
}
You can do this as below mentioned -:
You need to store the position of clicked button was. So initialize a variable in your class
int mButtonSelected = -1;
EDIT 1.
Then make a change to your isEnabled method
#Override
public boolean isEnabled(int position) {
if(position<mButtonSelected){
return false;
}
return true;
}
That will work it if any other button was clicked. but you have to do that in your onClick
mButtonSelected = position;
notifyDataSetChanged();
Let me it worked or not
EDIT
see below changes in your code-:
public class SelectStnListByRoute extends BaseAdapter {
Context context;
ArrayList<StnNames> stnList;
LayoutInflater layoutInflater = null;
ViewHolder viewHolder;
private int mLastClicked;
private SQLiteDB sqLiteDB;
int mArrivalSelected = -1;
int mDepartSelected = -1;
public SelectStnListByRoute(Context context, ArrayList<StnNames> stnList) {
super();
this.context = context;
this.stnList = stnList;
layoutInflater = LayoutInflater.from(context);
sqLiteDB = new SQLiteDB(context);
}
#Override
public int getCount() {
return stnList.size();
}
#Override
public Object getItem(int position) {
return stnList.get(position);
}
#Override
public long getItemId(int position) {
return stnList.indexOf(getItem(position));
}
public int getViewTypeCount() {
return 1;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
if (position <= mArrivalSelected) {
return false;
}
return true;
}
public boolean isEnabledd(int position) {
if (position <= mDepartSelected) {
return false;
}
return true;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int type = getItemViewType(position);
StnNames stnDetails = stnList.get(position);
viewHolder = new ViewHolder();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.footplate_custome_layout, null);
viewHolder.txtStnNAme = (TextView) convertView.findViewById(R.id.txtStnCode);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
viewHolder.txtStnDep = (TextView) convertView.findViewById(R.id.txtDepTime);
convertView.setTag(viewHolder);
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
} else {
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
}
viewHolder.txtStnNAme.setText(stnDetails.getStnCode());
if (!isEnabled(position)) {
if (position <= mArrivalSelected) {
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnArr.setEnabled(false);
if (position < mArrivalSelected) {
viewHolder.txtStnDep.setEnabled(false);
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#ffa500"));
}
}
} else {
viewHolder.txtStnArr.setEnabled(true);
viewHolder.txtStnDep.setEnabled(true);
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#b4b4b4"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#b4b4b4"));
}
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: ", String.valueOf(position));
mArrivalSelected = position;
arrivalClick(view);
notifyDataSetChanged();
}
});
if (!isEnabledd(position)) {
if (position <= mDepartSelected) {
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnArr.setEnabled(false);
viewHolder.txtStnDep.setEnabled(false);
} else {
viewHolder.txtStnArr.setEnabled(true);
viewHolder.txtStnDep.setEnabled(true);
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#b4b4b4"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#b4b4b4"));
}
}
viewHolder.txtStnDep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: ", String.valueOf(position));
mDepartSelected = position;
departureClick(view);
notifyDataSetChanged();
}
});
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
if (stnDetails.getArrivalTime() != null) {
viewHolder.txtStnArr.setText(stnDetails.getArrivalTime());
} else {
viewHolder.txtStnArr.setText("");
}
if (stnDetails.getDeptTime() != null) {
viewHolder.txtStnDep.setText(stnDetails.getDeptTime());
} else {
viewHolder.txtStnDep.setText("");
}
return convertView;
}
class ViewHolder {
TextView txtStnNAme, txtStnArr, txtStnDep;
StnNames pos;
int ref;
}
public void arrivalClick(View view) {
TextView textViewArrVal = (TextView) view.findViewById(R.id.txtArrivalTime);
StnNames listItemsArrr = (StnNames) textViewArrVal.getTag();
if (listItemsArrr.getArrivalTime() != getCurrentTime()) {
listItemsArrr.setArrivalTime(getCurrentTime());
int stnId = listItemsArrr.getStnId();
String arrClick = "arrival";
String upSideKm = listItemsArrr.getStnUpsideKm();
String downsideKm = listItemsArrr.getStnDownSideKm();
String arrTime = getCurrentTime();
/* sqLiteDB.open();
*//* long abc = sqLiteDB.insertJourneySchedule(stnId,arrTime,"",userId,journeyId,latitute,longitute,journyDate,arrClick);*//*
*//* long abcd = sqLiteDB.updateJourneySchedule(stnId,arrTime,"",userId,journeyId,latitute,longitute,journyDate,arrClick,downsideKm,upSideKm);
Log.e("arrclick",String.valueOf(abcd));*//*
sqLiteDB.close();*/
if (listItemsArrr.getArrivalTime() != null) {
int position = textViewArrVal.getSelectionStart();
textViewArrVal.setText(listItemsArrr.getArrivalTime());
} else {
textViewArrVal.setText("");
}
}
}
public void departureClick(View view) {
TextView textViewDepVal = (TextView) view.findViewById(R.id.txtDepTime);
StnNames listItemsDepp = (StnNames) textViewDepVal.getTag();
if (listItemsDepp.getDeptTime() != getCurrentTime()) {
listItemsDepp.setDeptTime(getCurrentTime());
String depTime = getCurrentTime();
int stnId = listItemsDepp.getStnId();
String depClick = "departure";
String upSideKm = listItemsDepp.getStnUpsideKm();
String downsideKm = listItemsDepp.getStnDownSideKm();
sqLiteDB.open();
/*long abc = sqLiteDB.insertJourneySchedule(stnId,"",depTime,userId,journeyId,latitute,longitute,journyDate,depClick);*/
/*long abcd = sqLiteDB.updateJourneySchedule(stnId,"",depTime,userId,journeyId,latitute,longitute,journyDate,depClick,downsideKm,upSideKm);
Log.e("depclick",String.valueOf(abcd));*/
sqLiteDB.close();
if (listItemsDepp.getDeptTime() != null) {
textViewDepVal.setText(listItemsDepp.getDeptTime());
} else {
textViewDepVal.setText("");
}
}
}
public String getCurrentTime() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String arrDate = mdformat.format(calendar.getTime());
return arrDate;
}
}
Get the position of the row which is clicked and then set onclick false for positions less than clicked position
as follows:
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: " , String.valueOf(position));
for (int i = 0; i < position; i++) {
viewHolder.txtStnArr.setEnable(false);
}
notifyDataSetChanged();
}
});
I use component android-section-list (http://code.google.com/p/android-section-list/) to create sections in my listView. How can I hide sections after push some button?
I try to do like
public void onClick(View v) {
switch(v.getId()) {
case R.id.sortTitle:
LayoutInflater inflater = (LayoutInflater) this.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View convertView = inflater.inflate(R.layout.market_list_separator, null, false);
TextView separatorLayout = (TextView) convertView.findViewById(R.id.section_view);
separatorLayout.setVisibility(View.GONE);
sectionAdapter.notifyDataSetChanged();
setButtonState(sortByTitle);
adapter.sort((Comparator<SectionListItem>) sortByTitle());
break;
}
}
But this way don't work.
My adapter put data in list rows and SectionListAdapter draw sections.
public class SectionListAdapter extends BaseAdapter implements ListAdapter,
OnItemClickListener {
private final DataSetObserver dataSetObserver = new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
updateSessionCache();
}
#Override
public void onInvalidated() {
super.onInvalidated();
updateSessionCache();
};
};
private final ListAdapter linkedAdapter;
private final Map<Integer, String> sectionPositions = new LinkedHashMap<Integer, String>();
private final Map<Integer, Integer> itemPositions = new LinkedHashMap<Integer, Integer>();
private final Map<View, String> currentViewSections = new HashMap<View, String>();
private int viewTypeCount;
protected final LayoutInflater inflater;
private View transparentSectionView;
private OnItemClickListener linkedListener;
public SectionListAdapter(final LayoutInflater inflater,
final ListAdapter linkedAdapter) {
this.linkedAdapter = linkedAdapter;
this.inflater = inflater;
linkedAdapter.registerDataSetObserver(dataSetObserver);
updateSessionCache();
}
private boolean isTheSame(final String previousSection,
final String newSection) {
if (previousSection == null) {
return newSection == null;
} else {
return previousSection.equals(newSection);
}
}
private synchronized void updateSessionCache() {
int currentPosition = 0;
sectionPositions.clear();
itemPositions.clear();
viewTypeCount = linkedAdapter.getViewTypeCount() + 1;
String currentSection = null;
final int count = linkedAdapter.getCount();
for (int i = 0; i < count; i++) {
final SectionListItem item = (SectionListItem) linkedAdapter
.getItem(i);
if (!isTheSame(currentSection, item.section)) {
sectionPositions.put(currentPosition, item.section);
currentSection = item.section;
currentPosition++;
}
itemPositions.put(currentPosition, i);
currentPosition++;
}
}
public synchronized int getCount() {
return sectionPositions.size() + itemPositions.size();
}
public synchronized Object getItem(final int position) {
if (isSection(position)) {
return sectionPositions.get(position);
} else {
final int linkedItemPosition = getLinkedPosition(position);
return linkedAdapter.getItem(linkedItemPosition);
}
}
public synchronized boolean isSection(final int position) {
return sectionPositions.containsKey(position);
}
public synchronized String getSectionName(final int position) {
if (isSection(position)) {
return sectionPositions.get(position);
} else {
return null;
}
}
public long getItemId(final int position) {
if (isSection(position)) {
return sectionPositions.get(position).hashCode();
} else {
return linkedAdapter.getItemId(getLinkedPosition(position));
}
}
protected Integer getLinkedPosition(final int position) {
return itemPositions.get(position);
}
#Override
public int getItemViewType(final int position) {
if (isSection(position)) {
return viewTypeCount - 1;
}
return linkedAdapter.getItemViewType(getLinkedPosition(position));
}
private View getSectionView(final View convertView, final String section) {
View theView = convertView;
if (theView == null) {
theView = createNewSectionView();
}
setSectionText(section, theView);
replaceSectionViewsInMaps(section, theView);
return theView;
}
protected void setSectionText(final String section, final View sectionView) {
final TextView textView = (TextView) sectionView.findViewById(R.id.listTextView);
textView.setText(section);
}
protected synchronized void replaceSectionViewsInMaps(final String section,
final View theView) {
if (currentViewSections.containsKey(theView)) {
currentViewSections.remove(theView);
}
currentViewSections.put(theView, section);
}
protected View createNewSectionView() {
return inflater.inflate(R.layout.section_view, null);
}
public View getView(final int position, final View convertView,
final ViewGroup parent) {
if (isSection(position)) {
return getSectionView(convertView, sectionPositions.get(position));
}
return linkedAdapter.getView(getLinkedPosition(position), convertView,
parent);
}
#Override
public int getViewTypeCount() {
return viewTypeCount;
}
#Override
public boolean hasStableIds() {
return linkedAdapter.hasStableIds();
}
#Override
public boolean isEmpty() {
return linkedAdapter.isEmpty();
}
#Override
public void registerDataSetObserver(final DataSetObserver observer) {
linkedAdapter.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(final DataSetObserver observer) {
linkedAdapter.unregisterDataSetObserver(observer);
}
#Override
public boolean areAllItemsEnabled() {
return linkedAdapter.areAllItemsEnabled();
}
#Override
public boolean isEnabled(final int position) {
if (isSection(position)) {
return true;
}
return linkedAdapter.isEnabled(getLinkedPosition(position));
}
public void makeSectionInvisibleIfFirstInList(final int firstVisibleItem) {
final String section = getSectionName(firstVisibleItem);
// only make invisible the first section with that name in case there
// are more with the same name
boolean alreadySetFirstSectionIvisible = false;
for (final Entry<View, String> itemView : currentViewSections
.entrySet()) {
if (itemView.getValue().equals(section)
&& !alreadySetFirstSectionIvisible) {
itemView.getKey().setVisibility(View.INVISIBLE);
alreadySetFirstSectionIvisible = true;
} else {
itemView.getKey().setVisibility(View.VISIBLE);
}
}
for (final Entry<Integer, String> entry : sectionPositions.entrySet()) {
if (entry.getKey() > firstVisibleItem + 1) {
break;
}
setSectionText(entry.getValue(), getTransparentSectionView());
}
}
public synchronized View getTransparentSectionView() {
if (transparentSectionView == null) {
transparentSectionView = createNewSectionView();
}
return transparentSectionView;
}
protected void sectionClicked(final String section) {
//
}
public void onItemClick(final AdapterView< ? > parent, final View view,
final int position, final long id) {
if (isSection(position)) {
sectionClicked(getSectionName(position));
} else if (linkedListener != null) {
linkedListener.onItemClick(parent, view,
getLinkedPosition(position), id);
}
}
public void setOnItemClickListener(final OnItemClickListener linkedListener) {
this.linkedListener = linkedListener;
}
}
Where can I put check for visibility in this Adapter?
This works but will be overwritten by the getView() method in the adapter . You must handle this in the adapter bcoz each time view becomes visible on the screen the View is updated so becomes visible in your case.
For the Data you are storing add a Visibility field ( by default keep it visible ) and change the Visibility to GONE in the onClick() method.
if you dont understand , post me your code and will let you know what changes to make.