Search code examples
androidonclickonclicklistener

how can use private void in the onclick?


how can use private void in the onclick?

when the user clicks the item, I hope I can calculate the like count, so how can I do?

this is my code

holder.like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toast.makeText(getApplicationContext(),"OK",Toast.LENGTH_SHORT).show();
                holder.likeCount.setText("1" + " likes");
                holder.likeImg.setImageResource(R.drawable.like);
                private void loadLikes() {
                    final ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
                    progressDialog.setMessage("Load...");
                    progressDialog.show();
                }
            }
        });

but it has an error code;

error: illegal start of expression private void loadLikes() {


Solution

  • Currently, you're trying to declare a function inside another function but java doesn't support nested functions (only through Lambda and anonymous classes). You can declare loadLikes() function outside the listener callback as follows:

     private void loadLikes() {
            ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
            progressDialog.setMessage("Load...");
            progressDialog.show();
        }
    

    And then call it inside onClick()

    holder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toast.makeText(getApplicationContext(),"OK",Toast.LENGTH_SHORT).show();
                holder.likeCount.setText("1" + " likes");
                holder.likeImg.setImageResource(R.drawable.like);
                loadLikes();
            }
        });
    

    cheers :)