I am trying to create a language selecting screen. I have a ListView and I am using custom adapter class. Upon selecting an item, I want to show a tick mark in the item. My ListView have a TextView` and an ImageView. How to achieve it?
Here is what I have tried already.
Any answer and suggestions are appreciated, Thanks in advance
public class customAdapter extends BaseAdapter {
String[] languages ;
Context mContext;
boolean isChecked = false;
public customAdapter(String[] languages, Context
mContext){
this.languages = languages;
this.mContext = mContext;
}
@Override
public int getCount() {
return languages.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)
mContext.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View rowView=
inflater.inflate(
R.layout.content_lang_list,parent,false);
TextView lang_text = (TextView)
rowView.findViewById(R.id.text_select_lang);
final ImageView image_tick = (ImageView)
rowView.findViewById(R.id.image_tick);
lang_text.setText(languages[position]);
image_tick.setImageResource(R.drawable.ic_checked);
return rowView;
}
public class ChangeLang extends AppCompatActivity {
private ListView languageList;
String[] languages = {"English","Portuguese","Arabic"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cahnge_lang);
languageList = (ListView)
findViewById(R.id.language_list);
final customAdapter mAdapter = new customAdapter(
languages,this);
languageList.setAdapter(mAdapter);
languageList.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
String selected = ((TextView)
view.findViewById(R.id.text_select_lang))
.getText().toString();
Object itemObject =parent.getAdapter()
.getItem(position);
LanguageSelect selectedLang =
(LanguageSelect)itemObject;
}
});
}
}
As a language selection screen, I assume you need to select only one item at a time. You have already added a boolean member isChecked;
but doesn't seems to be used anywhere.
What you need here is an int member - say, selectedItemPosition
whose initial value set as -1.
In other words, replace
boolean isChecked = false;
with
int selectedItemPosition = -1;
Add this to onItemClick()
selectedItemPosition = ((selectedItemPosition!=position)?position:-1);
notifyDataSetChanged();
Add this to your getView()
image_tick.setVisibility((selectedItemPosition=position)?View.VISIBLE:View.GONE);
ListViews
, follow view holder pattern to optimize performance.convertView
s to recycle views.image_tick.setImageResource(R.drawable.ic_checked);
with android:src="R.drawable.ic_checked"
in XML.