0
Hello, I have a problem that when showing the last item of the listview on the screen, the imagebuttom of the last item and the others of the screen stop working, when scrolling the screen again and hide this last item, all images of the screen start working again. This also happens with long click, which should open the contextmenu.
This problem does not present an error, it just does not show the contextmenu.
Activity
public class ClientsActivity extends AppCompatActivity {
/*-------------------------------------------+
| VARIAVEIS DE CONTROLE DA LISTAGEM DA QUERY |
+--------------------------------------------+*/
private int increment = 0; // NUMERO QUE SE ENCONTRA O SEQUENCIAL
private int limit = 20; // QUANTIDADE DE LISTAGEM POR VEZ NA QUERY
/*-------------------+
| LIST VIEW E FOOTER |
+--------------------+*/
private ListView lvClient;
private ClientListAdapter adapter;
private TextView emptyText;
/*---------------------------------------+
| TELA COM OBJETO VISUAL DE CARREGAMENTO |
+----------------------------------------+*/
private View loadView;
private boolean isLoading = false;
private Handler mHandler;
/*---------------------------------------+
| ALERT DIALOG COM AS OPCOES DE FILTRO |
+----------------------------------------+*/
private AlertDialog.Builder alertDialogFilter;
private AlertDialog.Builder alertDialogShow;
private int filtroSelecionado = 0;
private int showSelecionado = 0;
/*---------------------------------------+
| ALERT DIALOG COM AS OPCOES DE ORDENACAO |
+----------------------------------------+*/
private AlertDialog.Builder alertDialogOrderBy;
private int orderBySelecionado;
private HashMap<Integer, String> orderOptions = new HashMap<Integer, String>();
private HashMap<Integer, String> orderOrientationOptions = new HashMap<Integer, String>();
private String orderField = "A1_NOME";
private String orderOrientation = "ASC";
private String selectionFilter = "";
private String viewFilter = "";
private String[] selectionFilterArgs = null;
NavigationView navigation;
MenuClass menu = MenuClass.getInstance();
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private Cursor cursor;
/*------------------+
| CLASSE DE CRIACCO |
+-------------------+*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clients);
if (savedInstanceState != null) {
filtroSelecionado = savedInstanceState.getInt("filtroSelecionado");
showSelecionado = savedInstanceState.getInt("showSelecionado");
orderOrientation = savedInstanceState.getString("orderOrientation", orderOrientation);
}
//Controla tela ligada
if(Prefs.getBoolean(getApplicationContext(), Prefs.CHAVE_SCREEN)){
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
//Controla de rotação de tela
if (!Prefs.getBoolean(getApplicationContext(), Prefs.ROTATE_SCREEN)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
}
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_clients);
orderOptions.put(0, "CNPJ/CPF");
orderOptions.put(1, "Razão social");
orderOptions.put(2, "Nome fantasia");
orderOptions.put(3, "CEP");
orderOptions.put(4, "Cidade+Estado");
orderOrientationOptions.put(0, "Crescente");
orderOrientationOptions.put(1, "Decrescente");
/*------------------------------------------------------------------+
| CRIA OBJETO QUE IRA APRESENTAR O LOAD QUANDO FOR CARREGAR INFORMACCES |
+-----------------------------------------------------------------------+*/
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
loadView = li.inflate(R.layout.footer_view, null);
String orderBy = orderField + " " + orderOrientation;
/*----------+
| LIST VIEW |
+-----------+*/
mHandler = new MyHandler();
lvClient = (ListView)findViewById(R.id.listview_client);
emptyText = (TextView)findViewById(R.id.emptyText);
adapter = new ClientListAdapter(getApplicationContext(), getMoreData(selectionFilter, selectionFilterArgs, orderBy, true)){
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
view.setBackgroundColor(((position % 2 == 1) ? ResourcesCompat.getColor(getResources(), R.color.colorZebraListView, null) : Color.WHITE));
view.setLongClickable(true);
return view;
}
};
lvClient.addFooterView(loadView);
lvClient.setAdapter(adapter);
lvClient.removeFooterView(loadView);
lvClient.setEmptyView(emptyText);
registerForContextMenu(lvClient);
/*-------------------------------+
| QUANDO CLICAR NO ITEM DA LISTA |
+--------------------------------+*/
lvClient.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*--------------------------------------------------------------------+
| PASSA POR PARAMETRO O ID DO PRODUTO PARA PODER VISUALIZAR O DETALHE |
+---------------------------------------------------------------------+*/
startActivity(new Intent(ClientsActivity.this, ClientsDetailActivity.class).putExtra("nAt", (int) view.getTag()));
}
});
/*-------------------+
| CONTROLE DE SCROLL |
+--------------------+*/
lvClient.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int btn_initPosY = fab.getScrollY();
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
fab.animate().cancel();
fab.animate().translationYBy(350);
} else {
fab.animate().cancel();
fab.animate().translationY(btn_initPosY);
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
view.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
if(view.getLastVisiblePosition() == totalItemCount-1 && lvClient.getCount() >= limit && isLoading == false) {
isLoading = true;
Thread thread = new ThreadGetMoreData();
thread.start();
}
}
});
//Monta o Filtro
alertDialogFilter = new AlertDialog.Builder(this);
buildFilterDialog();
alertDialogShow = new AlertDialog.Builder(this);
buildShowDialog();
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Snackbar.make(view, "Snackbar message", Snackbar.LENGTH_LONG).setAction("Action", null).show();
startActivity(new Intent(ClientsActivity.this, NewSalesActivity.class));
}
});
navigation = (NavigationView) findViewById(R.id.nav_view);
navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
menu.choiceMenu(getApplicationContext(), id);
finish();
return false;
}
});
navigation.setItemIconTintList(null);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
int id = getIdCli(info);
menu.setHeaderTitle(getNameCli(info)) ;
menu.add(Menu.NONE, id , Menu.NONE, R.string.TITLE_MENU_FINANCEIRO_CLIENTE );
menu.add(Menu.NONE, id , Menu.NONE, R.string.TITLE_MENU_VISUALIZAR_ITEM );
menu.add(Menu.NONE, id , Menu.NONE, R.string.TITLE_MENU_DOCUMENTO_CLIENTE );
menu.add(Menu.NONE, id , Menu.NONE, R.string.TITLE_MENU_COMPRAS_CLIENTE );
menu.add(Menu.NONE, id , Menu.NONE, R.string.TITLE_MENU_PEDIDOS_CLIENTE );
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == getResources().getString(R.string.TITLE_MENU_FINANCEIRO_CLIENTE)) {
cursor = new DBController(getBaseContext()).selectListData("SE1 JOIN SA1 AS SA1 ON (A1_COD = E1_CLIENTE AND A1_LOJA = E1_LOJA) ", null, "SA1.id = ? ", new String[]{String.valueOf(item.getItemId())}, null);
Context context = getApplicationContext();
if (cursor.getCount() == 0) {
Toast.makeText(context, "Nenhum título para este cliente!", Toast.LENGTH_LONG).show();
} else {
startActivity(new Intent(ClientsActivity.this, FinancialDetailActivity.class).putExtra("nAt", item.getItemId()));
}
} else { return false; }
return true;
}
public String getNameCli(AdapterView.AdapterContextMenuInfo info) {
return ((TextView) info.targetView.findViewById(R.id.tv_name)).getText().toString();
}
public int getIdCli(AdapterView.AdapterContextMenuInfo info) {
return Integer.parseInt(((TextView) info.targetView.findViewById(R.id.tv_cod)).getText().toString());
}
public void doEatIn(MenuItem mi) {
Toast.makeText(this, "Your table will be ready soon", Toast.LENGTH_SHORT).show();
}
public void doTakeOut(MenuItem mi) {
Toast.makeText(this, "Please pick up at the take-out window", Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return (true);
}
public class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
// HABILITA NO RADAPE O CARREGANDO
lvClient.addFooterView(loadView);
break;
case 1:
adapter.addListItemToAdapter((ArrayList<Client>) msg.obj); //Update data adapter and UI
lvClient.removeFooterView(loadView); //Remove loading view after update listview
isLoading = false;
break;
default:
break;
}
}
}
/*------------------------------------+
| CRIA O ARRAY PARA MONTAR O LISTVIEW |
+-------------------------------------+*/
private ArrayList<Client> getMoreData(String selection,String[] selectionArgs, String orderBy, boolean isLimite) {
if (!viewFilter.trim().equals("") && !selection.trim().equals("")) {
selection = " AND " + selection;
}
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String formDate = sdf.format(c.getTime()).toString();
ArrayList<Client> lst = new ArrayList<>();
DBController dbCtrl = new DBController(getBaseContext());
String[] fieldTable = {"SA1.id", "A1_CGC", "A1_NOME", "A1_NREDUZ", "A1_END", "A1_MUN", "A1_EST", "A1_CEP", "A1_LC", "ifnull((SELECT SUM(E1_SALDO) FROM SE1 WHERE A1_COD = E1_CLIENTE AND A1_LOJA = E1_LOJA AND E1_VENCTO >= '"+formDate+"'),0) SALDO_A_DEV ", "ifnull((SELECT SUM(E1_SALDO) FROM SE1 WHERE A1_COD = E1_CLIENTE AND A1_LOJA = E1_LOJA AND E1_VENCTO < '"+formDate+"'),0) SALDO_DEV "};
Cursor cursor = dbCtrl.selectListDataOrder("SA1", fieldTable, viewFilter+selection, selectionArgs, orderBy, (isLimite ? String.valueOf(increment) + "," + String.valueOf(limit) : null));
increment += limit;
while (cursor.moveToNext()) {
DecimalFormat formatter = new DecimalFormat(",##0.00");
String creditLimit = formatter.format(cursor.getDouble(cursor.getColumnIndex("A1_LC")));
lst.add(new Client(
cursor.getInt(cursor.getColumnIndex("id")),
cursor.getString(cursor.getColumnIndex("A1_CGC")),
cursor.getString(cursor.getColumnIndex("A1_NREDUZ")),
cursor.getString(cursor.getColumnIndex("A1_NOME")),
cursor.getString(cursor.getColumnIndex("A1_END")),
cursor.getString(cursor.getColumnIndex("A1_MUN")),
cursor.getString(cursor.getColumnIndex("A1_EST")),
cursor.getString(cursor.getColumnIndex("A1_CEP")),
"R$ "+creditLimit,
cursor.getDouble(cursor.getColumnIndex("SALDO_A_DEV")),
cursor.getDouble(cursor.getColumnIndex("SALDO_DEV"))
));
}
return lst;
}
public class ThreadGetMoreData extends Thread {
@Override
public void run() {
String orderBy = orderField + " " + orderOrientation;
mHandler.sendEmptyMessage(0); //Add footer view after get data
ArrayList<Client> lstResult = getMoreData(selectionFilter, selectionFilterArgs, orderBy, true); //Search more data
Message msg = mHandler.obtainMessage(1, lstResult); //Send the result to Handle
mHandler.sendMessage(msg);
}
}
public void updateListItens(String selection, String[] selectionArgs) {
// RESET LIMIT
increment = 0;
limit = 20;
String orderBy = orderField + " " + orderOrientation;
lvClient.addFooterView(loadView);
lvClient.setAdapter(null);
lvClient.removeFooterView(loadView);
lvClient.setEmptyView(emptyText);
adapter = new ClientListAdapter(getApplicationContext(), getMoreData(selection, selectionArgs, orderBy, true)) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
view.setBackgroundColor(((position % 2 == 1) ? ResourcesCompat.getColor(getResources(), R.color.colorZebraListView, null) : Color.WHITE));
return view;
}
};
adapter.notifyDataSetChanged(); // TENTA ORDERNAR
lvClient.addFooterView(loadView);
lvClient.setAdapter(adapter);
lvClient.removeFooterView(loadView);
lvClient.setEmptyView(emptyText);
}
private void buildFilterDialog() {
final String[] labels = getResources().getStringArray(R.array.rg_filter_client);
alertDialogFilter.setTitle("Filtrar por");
alertDialogFilter.setSingleChoiceItems(labels, filtroSelecionado, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int posicao) {
alertDialogFilter.setSingleChoiceItems(labels, posicao, this);
dialogInterface.dismiss();
filtroSelecionado = posicao;
if (filtroSelecionado == 0) {
updateListItens(null, null);
}
}
});
}
private void buildShowDialog() {
final String[] labels = getResources().getStringArray(R.array.rg_show_clients);
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
final String formDate = sdf.format(c.getTime()).toString();
alertDialogShow.setTitle("Mostrar");
alertDialogShow.setSingleChoiceItems(labels, showSelecionado, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int posicao) {
alertDialogShow.setSingleChoiceItems(labels, posicao, this);
dialogInterface.dismiss();
showSelecionado = posicao;
if (showSelecionado == 0) {
viewFilter = "";
updateListItens(selectionFilter, selectionFilterArgs);
}
if (showSelecionado == 1) {
viewFilter = "A1_ISINVOICE > 0";
updateListItens(selectionFilter, selectionFilterArgs);
}
if (showSelecionado == 2) {
viewFilter = "A1_ISINVOICE <= 0";
updateListItens(selectionFilter, selectionFilterArgs);
}
if (showSelecionado == 3) {
viewFilter = " SALDO_A_DEV >= 0 AND SALDO_DEV <= 0 ";
updateListItens(selectionFilter, selectionFilterArgs);
}
if (showSelecionado == 4) {
viewFilter = " SALDO_DEV > 0 ";
updateListItens(selectionFilter, selectionFilterArgs);
}
if (showSelecionado == 5) {
viewFilter = " ((A1_ZCKALV1 != '' AND A1_ZDTALV1 != '' AND A1_ZDTALV1 < '"+formDate+"') OR (A1_ZCKALV2 != '' AND A1_ZDTALV2 != '' AND A1_ZDTALV2 < '"+formDate+"') OR (A1_ZCKALV3 != '' AND A1_ZDTALV3 != '' AND A1_ZDTALV3 < '"+formDate+"')) ";
updateListItens(selectionFilter, selectionFilterArgs);
}
if (showSelecionado == 6) {
viewFilter = " (((A1_ZNMALV1 = '' AND A1_ZDTALV1 = '') OR A1_ZDTALV1 >= '"+formDate+"') AND ((A1_ZNMALV2 = '' AND A1_ZDTALV2 = '') OR A1_ZDTALV2 >= '"+formDate+"') AND ((A1_ZNMALV3 = '' AND A1_ZDTALV3 = '') OR A1_ZDTALV3 >= '"+formDate+"')) ";
updateListItens(selectionFilter, selectionFilterArgs);
}
}
});
}
public void OrderScreen() {
final Dialog dialog = new Dialog(ClientsActivity.this);
dialog.setContentView(R.layout.custom_dialog_order);
dialog.getWindow().setLayout(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
dialog.setTitle("Ordenação");
final Button btnOk = (Button) dialog.findViewById(R.id.ok);
final Button btnCancel = (Button) dialog.findViewById(R.id.cancel);
final RadioGroup rgV = (RadioGroup) dialog.findViewById(R.id.radiogroupVertical);
final RadioGroup rgH = (RadioGroup) dialog.findViewById(R.id.radiogroupHorizontal);
final TextView tvText = (TextView) dialog.findViewById(R.id.textView2);
tvText.setVisibility(View.GONE);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final LinearLayout li = new LinearLayout(ClientsActivity.this);
li.setLayoutParams(params);
li.setOrientation(LinearLayout.VERTICAL);
for (Map.Entry<Integer, String> entry : orderOptions.entrySet()) {
RadioButton radioButton = new RadioButton(ClientsActivity.this);
radioButton.setText(entry.getValue());
radioButton.setId(entry.getKey());
RadioGroup.LayoutParams paramsRadio = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
rgV.addView(radioButton, paramsRadio);
}
((ViewGroup) dialog.findViewById(R.id.radiogroupVertical)).addView(li);
if (orderField.equals("A1_CGC")) {
rgV.check(0);
} else if (orderField.equals("A1_NOME")) {
rgV.check(Integer.parseInt("1"));
} else if (orderField.equals("A1_NREDUZ")) {
rgV.check(Integer.parseInt("2"));
} else if (orderField.equals("A1_CEP")) {
rgV.check(Integer.parseInt("3"));
} else if (orderField.equals("A1_MUN, A1_EST")) {
rgV.check(Integer.parseInt("4"));
}
final LinearLayout li2 = new LinearLayout(ClientsActivity.this);
li2.setLayoutParams(params);
li2.setOrientation(LinearLayout.HORIZONTAL);
for (Map.Entry<Integer, String> entry : orderOrientationOptions.entrySet()) {
RadioButton radioButton = new RadioButton(ClientsActivity.this);
radioButton.setText(entry.getValue());
radioButton.setId(entry.getKey());
RadioGroup.LayoutParams paramsRadio = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
rgH.addView(radioButton, paramsRadio);
}
((ViewGroup) dialog.findViewById(R.id.radiogroupHorizontal)).addView(li2);
if (orderOrientation.equals("DESC")) {
rgH.check(Integer.parseInt("1"));
} else {
rgH.check(0);
}
btnOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int radioOption = rgV.getCheckedRadioButtonId();
int radioOrientation = rgH.getCheckedRadioButtonId();
if (radioOption == 0) {
orderField = "A1_CGC";
} else if (radioOption == 1) {
orderField = "A1_NOME";
} else if (radioOption == 2) {
orderField = "A1_NREDUZ";
} else if (radioOption == 3) {
orderField = "A1_CEP";
} else if (radioOption == 4) {
orderField = "A1_MUN, A1_EST";
}
if (radioOrientation == 0) {
orderOrientation = "ASC";
} else if (radioOrientation == 1) {
orderOrientation = "DESC";
}
updateListItens(selectionFilter, selectionFilterArgs);
dialog.dismiss();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
}
Adapter
public class ClientListAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Client> mClientList;
Utils utils = Utils.getInstance();
//Constructor
public ClientListAdapter(Context mContext, ArrayList<Client> mClientList) {
this.mContext = mContext;
this.mClientList = mClientList;
}
public void addListItemToAdapter(ArrayList<Client> list) {
//Add list to current array list of data
mClientList.addAll(list);
//Notify UI
this.notifyDataSetChanged();
}
@Override
public int getCount() {
return mClientList.size();
}
@Override
public Object getItem(int position) {
return mClientList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(mContext, R.layout.item_client_list, null);
TextView tv_cod = (TextView) v.findViewById(R.id.tv_cod);
TextView tv_cnpj = (TextView) v.findViewById(R.id.tv_cpnj);
TextView tv_fantasyName = (TextView) v.findViewById(R.id.tv_fantasyName);
TextView tv_name = (TextView) v.findViewById(R.id.tv_name);
TextView tv_end = (TextView) v.findViewById(R.id.tv_end);
TextView tv_creditLimit = (TextView) v.findViewById(R.id.tv_creditLimit);
TextView tvSaldoAVencer = (TextView) v.findViewById(R.id.tv_saldo_a_vencer);
TextView tvSaldoVencido = (TextView) v.findViewById(R.id.tv_saldo_vencido);
ImageButton imageButton = (ImageButton) v.findViewById(R.id.imagebutton);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.showContextMenu();
}
});
Mask mask = Mask.getInstance();
DecimalFormat formatter = new DecimalFormat(",##0.00");
tv_cod.setText(String.valueOf(mClientList.get(position).getId()));
tv_cnpj.setText(mask.CGC(mClientList.get(position).getCod()));
tv_fantasyName.setText(mClientList.get(position).getFantasyName());
tv_name.setText(mClientList.get(position).getName());
tv_end.setText(mClientList.get(position).getEnd() + ", " + utils.maskCEP(mClientList.get(position).getCep()) + ", " + mClientList.get(position).getCidade() + " - " + mClientList.get(position).getUf());
tv_creditLimit.setText("Limite: R$ " + mClientList.get(position).getCreditLimit());
tvSaldoAVencer.setText("A vencer: R$ " + formatter.format(mClientList.get(position).getSaldoADev()));
tvSaldoVencido.setText("Vencido: R$ " + formatter.format(mClientList.get(position).getSaldoDev()));
//Save client id to tag
v.setTag(mClientList.get(position).getId());
return v;
}
public ArrayList<Client> getmClientList() {
return mClientList;
}
public void setmClientList(ArrayList<Client> mClientList) {
this.mClientList = mClientList;
}
}
What happens is that the long click is not even the real problem, I tried to reference it to try to improve understanding, but it did not work very well. I did a test taking the limit and the thread letting list all the records on the screen, and in the last item worked normal click on imagebuttom.
– Scussel
@Scussel your mistake is definitely in that part of the conditions.. Because instead of "listening" the scrollVoce does not control by the item being displayed in the list (if it is the 1st, 2nd, 3rd, etc.) since the list grows only when it arrives at the very end.. an idea that came to me today
– leofontes
I didn’t quite understand the idea, can exemplify ?
– Scussel