我需要使用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]);
}
}
我的尝试是:
ProgramViewHolder finalHolder = holder;
singleItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(programName[position] == "ex1") {
finalHolder.programTitle.setText("expected text");
}
}
});
这会暂时更改文本,但每次在列表中向下移动并再次向上移动时,文本都会恢复为默认文本。
1条答案
按热度按时间whlutmcx1#
若要修正此问题,您可以在设定
programTitle
的文字之后,尝试更新界面卡中的programName
数组。以下是您可以执行此操作的方法:
这将用新文本更新programName数组,当您上下滚动列表时,将显示新文本。您也可以在更新programName数组后尝试使用notifyDataSetChanged()方法用更新的文本刷新列表视图。
以下是实现这些更改后
onClick()
方法的外观: