I need to change the clicked text in listview using a ProgramAdapter.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
String[] programName = {"ex1", "ex2", "ex3"}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvProgram = findViewById(R.id.listView);
ProgramAdapter programAdapter = new ProgramAdapter(this, programName);
lvProgram.setAdapter(programAdapter);
}}
ProgramAdapter.java:
public class ProgramAdapter extends ArrayAdapter<String> {
Context context;
String[] programName;
public ProgramAdapter(Context context, String[] programName) {
super(context, R.layout.single_item2, R.id.titulo, programName);
this.context = context;
this.programName = programName;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View singleItem = convertView;
ProgramViewHolder holder = null;
if(singleItem == null){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
singleItem = layoutInflater.inflate(R.layout.single_item2, parent, false);
holder = new ProgramViewHolder(singleItem);
singleItem.setTag(holder);
}
else{
holder = (ProgramViewHolder) singleItem.getTag();
}
holder.programTitle.setText(programName[position]);
}
}
My attempt was that:
ProgramViewHolder finalHolder = holder;
singleItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(programName[position] == "ex1") {
finalHolder.programTitle.setText("expected text");
}
}
});
This changes the text for a moment, but every time you go down the list and up again, the text goes back to the default text.
CodePudding user response:
To fix this issue, you can try to update the programName
array in the adapter after setting the text of the programTitle
.
Here's how you can do that:
@Override
public void onClick(View view) {
if(programName[position] == "ex1") {
finalHolder.programTitle.setText("expected text");
programName[position] = "expected text"; // update the programName array
}
}
This will update the programName array with the new text, and when you scroll up and down the list, the new text will be displayed. You can also try using the notifyDataSetChanged() method after updating the programName array to refresh the listview with the updated text.
Here's how your onClick()
method can look like after implementing these changes:
@Override
public void onClick(View view) {
if(programName[position] == "ex1") {
finalHolder.programTitle.setText("expected text");
programName[position] = "expected text"; // update the programName array
notifyDataSetChanged(); // refresh the listview
}
}