I am new to Android programming. I intend to make a shopping List using a ListView such that the user can strike through items on the list that he has bought. it should be such that
List is made.
He can strike through items bought.
He can add items using the EditText and the Add button at the bottom of the layout.
List is rendered after adding items like on point 3 with the stroke through items maintained.
On starting I click for many of the initial items I added in my program to have a stroke through and then I start adding items, I get an unexpected behaviour in the List. Some of the newly added items get a stroke through after I click ADD right from the outset when I havent even clicked for them to have a stroke through. Some of them dont. I dont understand this behaviour. Is it because of some property of ListView?
ArrayList<String> shoppingList = new ArrayList<>();;
ArrayList<String> strikeThroughList = null;
ArrayList<String> strikeThroughText = null;
ArrayAdapter<String> adapter = null;
ListView lv = null;
Button addBtn=null;
EditText addEdtTxt=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addBtn=findViewById(R.id.addBtn);
addBtn.setOnClickListener(this::btnClick);
//shoppingList = new ArrayList<>();
strikeThroughList = new ArrayList<>();
strikeThroughText= new ArrayList<>();
//One way to populate List
Collections.addAll(shoppingList, "Eggs", "Yogurt", "Milk", "Bananas", "Apples", "Tide with bleach", "Cascade");
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, shoppingList);
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mnu,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==R.id.clrList)
{
shoppingList.clear();
lv.setAdapter(adapter);
}
return super.onOptionsItemSelected(item);
}
public void btnClick(View view) {
if(view.getId()==R.id.addBtn){ addEdtTxt=findViewById(R.id.addEdtTxt);
adapter.add(addEdtTxt.getText().toString());
adapter.notifyDataSetChanged();
}
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
TextView text = (TextView) view;
text.setPaintFlags(text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}