Accessing a specific component within a listview

Asked

Viewed 98 times

0

I have a music list with a favorite icon, when the user clicks on this icon I want to change the color of the icon as the like action.

In this structure I have an Activity, a listview in this Activity, an Adapter class that inflates the layout list_hinos.xml and it is in this layout that Imageview ic_favorite_border is, when the user clicks on Imageview(only in Imageview itself and not on the entire line because the entire line has another action) I will change the image to R.drawable.ic_favorite.

The way that the code is now, when I click on Imagemview gives an error null Pointer Exception because it does not assemleha the layout component with Activity because it has another layout.

I’m trying to perform this action inside the actibity, I don’t know if it should be there or on the Adapter:

Mocidadeactivity.class

public class MocidadeActivity extends AppCompatActivity {
    //ATRIBUTOS
    private ImageView imLike;
    private ListView listView;
    private ArrayList<Hinos> arrayList;
    private ArrayAdapter adapter;
    private DatabaseReference reference;
    private ValueEventListener valueEventListener;
    private Boolean acaoCurtir;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mocidade);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        //DEFININDO A TRANSIÇÃO DE ENTRADA DA ACTIVITY
        if (Build.VERSION.SDK_INT >= 22){
            Slide s = new Slide();
            s.setDuration(1000);
            getWindow().setEnterTransition(s);
        }

        //Tentando instanciar o imageview
        imLike = findViewById(R.id.img_like_lista_hinos);

        //Montando a lista de exibição dos hinos
        listView = (ListView) findViewById(R.id.lv_hinos);

        arrayList = new ArrayList<>();
        adapter = new HinosAdapter(MocidadeActivity.this, arrayList);
        listView.setAdapter(adapter);

        //*************** FIREBASE INICIO ************************/
        reference = ConfiguracaoFirebase.getFirebaseReference().child("MOCIDADE")
                .child("HINOS");
        reference.orderByKey();

        valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                arrayList.clear();

                //Listando os hinos
                for (DataSnapshot data: dataSnapshot.getChildren()){
                    Hinos hinos = data.getValue(Hinos.class);
                    arrayList.add(hinos);
                }

                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };

        //*************** FIREBASE FIM ************************/

        /**************** COMPONENTES DA TELA ********************/
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int position, long l) {

                if (acaoCurtir == false){
                    try{
                        Hinos hinos = arrayList.get(position);
                        //salvando no shared para ser utilizado depois
                        SharedPreferencias preferences = new SharedPreferencias(MocidadeActivity.this);
                        preferences.salvarHinoPreferences(hinos.getNumero(), hinos.getTitulo(), hinos.getCantor(), hinos.getUrl());

                        Intent letraA = new Intent(MocidadeActivity.this, LetraHinosActivity.class);
                        startActivity(letraA);

                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }

            }
        });
    }

/******************************* METODOS *********************************/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_mocidade, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.mn_add_hino:

            if (Atalhos.verificarRegente(getApplicationContext()) == true) {
                AdicionarHinoFragment hinoFragment = new AdicionarHinoFragment();
                hinoFragment.show(MocidadeActivity.this.getSupportFragmentManager(), "Alert Adicionar Hino");
            } else {
                Atalhos.acessoNegado(MocidadeActivity.this);
            }
            break;
    }
    return super.onOptionsItemSelected(item);
}

public void favoritarHino(View view){

    Log.d("CURTIR", "Acessou esse metodo");
    int pos = listView.getPositionForView(view);

    acaoCurtir = true;

    Toast.makeText(this, "Clicou no curtir", Toast.LENGTH_SHORT).show();

    imLike.setImageResource(R.drawable.ic_favorite);
}

@Override
protected void onStart() {
    super.onStart();
    reference.addValueEventListener(valueEventListener);
    acaoCurtir = false;
}

@Override
protected void onStop() {
    super.onStop();
    reference.removeEventListener(valueEventListener);
    acaoCurtir = false;
}

Hinosadapter.class

public class HinosAdapter extends ArrayAdapter<Hinos>{
//ATRIBUTOS
Context context;
private ArrayList<Hinos> arrayList;

public HinosAdapter(@NonNull Context c, ArrayList<Hinos> objects) {
    super(c, 0, objects);
    this.context = c;
    this.arrayList = objects;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View view = null;

    //Validando e criando a lista de hinos
    if (arrayList != null){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);

        //montando a view a partir do XML
        view = inflater.inflate(R.layout.lista_hinos, parent, false);

        //Recuperando os elementos para exibição
        TextView tvNumero = view.findViewById(R.id.tv_num_hino);
        TextView tvTitulo = view.findViewById(R.id.tv_titulo_hino);
        TextView tvCantor = view.findViewById(R.id.tv_cantor_hino);
        final ImageView imLike = view.findViewById(R.id.img_like_lista_hinos);

        Hinos hinos = arrayList.get(position);
        tvNumero.setText(hinos.getNumero());
        tvCantor.setText(hinos.getCantor());
        tvTitulo.setText(hinos.getTitulo());
        imLike.setImageResource(R.drawable.ic_favorite_border);


        /*imLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });*/

    }
    return view;
}

}

Mocidadeactivity.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<ListView
    android:id="@+id/lv_hinos"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>

xml listing.

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/tv_num_hino"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:text="33"
    android:textSize="@dimen/numero_hino"
    android:layout_marginLeft="16dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="6dp" />

<TextView
    android:id="@+id/tv_titulo_hino"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Extraordinário"
    android:textSize="@dimen/nome_hino"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="6dp"
    app:layout_constraintLeft_toRightOf="@+id/tv_num_hino"
    android:layout_marginLeft="24dp" />

<TextView
    android:id="@+id/tv_cantor_hino"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Jota A"
    android:textSize="@dimen/cantor"
    android:textStyle="italic"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/tv_titulo_hino"
    app:layout_constraintLeft_toRightOf="@+id/tv_num_hino"
    android:layout_marginLeft="24dp" />

<ImageView
    android:id="@+id/img_like_lista_hinos"
    android:layout_width="25dp"
    android:layout_height="25dp"
    android:layout_marginRight="36dp"
    android:layout_marginTop="24dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:onClick="favoritarHino"/>

  </android.support.constraint.ConstraintLayout>

1 answer

1

I was able to find the solution to my problem and would like to share, in case anyone else has the same scenario I had, the solution was very obvious, ie the layout containing the component in which I want to implement the action is being inflated inside the Adapter, so that’s where I need to put it, inside the same getView, I do the implentation of the click event and the code itself already brings me the change in the clicked position of the list: my problem was solved with only this code in getView of the Hinosadapter class:

imLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context, "clicado na posição: "+position, Toast.LENGTH_SHORT).show();
                imLike.setImageResource(R.drawable.ic_favorite);
            }
        });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.