I hava a listview with each row containing a textview and checkbox. Now what I want is that when I click the textview the checkbox must be checked accordingly. I tried using this code:
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "You have selected item no."
+(position+1)+"", Toast.LENGTH_SHORT).show();
super.onListItemClick(l, v, position, id);
if (v != null) {
CheckBox checkBox = (CheckBox)v.findViewById(R.id.Checkbox);
checkBox.setChecked(!checkBox.isChecked());
}
}
Here's my whole code:
public class MyActivity3 extends Activity {
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my3);
Button m = (Button) findViewById(R.id.button3);
tv = (TextView) findViewById(R.id.textViewcat);
Typeface typeface = Typeface.createFromAsset(getAssets(), "BebasNeue Bold.ttf");
tv.setTypeface(typeface);
String[] listArray = new String[] { "All", "Friends & Family", "Sports", "Outside", "At School", "Fitness", "Photography", "Food", "Beach", "Money" };
SharedPreferences sharedPreferences = getSharedPreferences("status", MODE_PRIVATE);
Boolean[] checkedStatus = new Boolean[listArray.length];
for ( int index = 0; index < checkedStatus.length; index++)
checkedStatus[index] = sharedPreferences.getBoolean(Integer.toString(index), false);
ListView listView = (ListView) findViewById(R.id.listView);
MyAdapter adapter = new MyAdapter(this, R.layout.row_layout, listArray, checkedStatus);
listView.setAdapter(adapter);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "You have selected item no."
+(position+1)+"", Toast.LENGTH_SHORT).show();
super.onListItemClick(l, v, position, id);
if (v != null) {
CheckBox checkBox = (CheckBox)v.findViewById(R.id.chk);
checkBox.setChecked(!checkBox.isChecked());
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.animation8, R.anim.animation7);
}
}
Now in the line super.onListItemClick(l, v, position, id); , onListItemClick is red. Any idea why?
Cristiano
Because Activity doesn't have an onListItemClick(), so when you are calling super.onListItemClick() , it throws a compile Time Error because there is no such function in it's parent class. if you want use onListItemClick() you should extends your class from ListActivity.
Use following code to work with itemClickListener.
We need to set OnItemclickListener with list view object. in which we override onItemClick method.
update
public class MyActivity3 extends Activity {
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my3);
Button m = (Button) findViewById(R.id.button3);
tv = (TextView) findViewById(R.id.textViewcat);
Typeface typeface = Typeface.createFromAsset(getAssets(), "BebasNeue Bold.ttf");
tv.setTypeface(typeface);
String[] listArray = new String[] { "All", "Friends & Family", "Sports", "Outside", "At School", "Fitness", "Photography", "Food", "Beach", "Money" };
SharedPreferences sharedPreferences = getSharedPreferences("status", MODE_PRIVATE);
Boolean[] checkedStatus = new Boolean[listArray.length];
for ( int index = 0; index < checkedStatus.length; index++)
checkedStatus[index] = sharedPreferences.getBoolean(Integer.toString(index), false);
ListView listView = (ListView) findViewById(R.id.listView);
MyAdapter adapter = new MyAdapter(this, R.layout.row_layout, listArray, checkedStatus);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// do here whatever you want :-)
Toast.makeText(getApplicationContext(), "You have selected item no."
+(position+1)+"", Toast.LENGTH_SHORT).show();
if (view != null) {
CheckBox checkBox = (CheckBox)v.findViewById(R.id.chk);
checkBox.setChecked(!checkBox.isChecked());
}
}
});
}
Related
I am creating a gpa calculator and have used a spinner to populate the grades. how do I multiply the value in spinner2 which is credits to the grade points value in textview1 so it displays the result in textview2 which is the gradevalue.(should be something like: gradevalue=credits*gradepoints)
`public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] grades ={"A","B+","B","C+","C", "D+", "D", "E"};
String[] credits ={"1","2","3","4"};
double [] points1 = {4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 1.0, 0 };
Spinner spinner;
TextView TextView1;
TextView TextView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView1 = (TextView) findViewById(R.id.gradePoints);
TextView2 = (TextView) findViewById(R.id.gradeValue);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, grades);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter1);
spinner.setOnItemSelectedListener(onItemSelectedListener1);
Spinner spin2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, credits);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin2.setAdapter(adapter2);
spin2.setOnItemSelectedListener(this);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String s1 = String.valueOf(points1[position]);
TextView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
public void onItemSelected(AdapterView<?> parent, View v, int position, long id ){
Spinner spin = (Spinner)parent;
Spinner spin2 = (Spinner)parent;
if(spin.getId() == R.id.spinner)
{
Toast.makeText(this, "Your choice :" + grades[position],Toast.LENGTH_SHORT).show();
}
if(spin2.getId() == R.id.spinner2)
{
Toast.makeText(this, "Your choice :" + credits[position],Toast.LENGTH_SHORT).show();
}
}
public void onNothingSelected(AdapterView<?> parent){
Toast.makeText(this, "Choose grades :", Toast.LENGTH_SHORT).show();
}
}
enter code here`
you just need to set Onitemselected listener on spinner depending upon selected item's index you can change textview's value.Hope it will help you
You need to set the text on your spinner and you can get it with a method like :
getSelectedValue() and you add +1 on it because it start at 0.
Hey KunjiDaniel this is working at my end.Please check this Spinner spinner;
ArrayAdapter<String> adapter;
String[] spinnerData = {"1", "3", "4", "5", "6"};
TextView text2, resultText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_spinner);
spinner = (Spinner) findViewById(R.id.spinner);
text2 = (TextView) findViewById(R.id.numbr2);
text2.setText(String.valueOf(3));
resultText = (TextView) findViewById(R.id.result);
adapter = new ArrayAdapter<String>(SampleSpinner.this, android.R.layout.simple_dropdown_item_1line, spinnerData);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
String selected_value = adapterView.getItemAtPosition(position).toString();
changeResultantValues(selected_value);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
int value = 0;
public void changeResultantValues(String spinnerSelected) {
if (!spinnerSelected.equals("")) {
value = Integer.parseInt(spinnerSelected);
}
String textview2Value = text2.getText().toString();
int value2 = Integer.parseInt(textview2Value);
String resultant = String.valueOf(value * value2);
resultText.setText(resultant);
}
i want to multiply the credits by the gradePoints to return the gradevalue in textview2. how do i do that? the credits is the second spinner. `public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] grades ={"A","B+","B","C+","C", "D+", "D", "E"};
String[] credits ={"1","2","3","4"};
double [] points1 = {4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 1.0, 0 };
Spinner spinner;
TextView TextView1;
TextView TextView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView1 = (TextView) findViewById(R.id.gradePoints);
TextView2 = (TextView) findViewById(R.id.gradeValue);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, grades);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter1);
spinner.setOnItemSelectedListener(onItemSelectedListener1);
Spinner spin2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, credits);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin2.setAdapter(adapter2);
spin2.setOnItemSelectedListener(this);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String s1 = String.valueOf(points1[position]);
TextView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
public void onItemSelected(AdapterView<?> parent, View v, int position, long id ){
Spinner spin = (Spinner)parent;
Spinner spin2 = (Spinner)parent;
if(spin.getId() == R.id.spinner)
{
Toast.makeText(this, "Your choice :" + grades[position],Toast.LENGTH_SHORT).show();
}
if(spin2.getId() == R.id.spinner2)
{
Toast.makeText(this, "Your choice :" + credits[position],Toast.LENGTH_SHORT).show();
}
}
public void onNothingSelected(AdapterView<?> parent){
Toast.makeText(this, "Choose grades :", Toast.LENGTH_SHORT).show();
}
}
`
Maybe you can try this:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String[] grades ={"A","B+","B","C+","C", "D+", "D", "E"};
String[] credits ={"1","2","3","4"};
double [] points1 = {4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 1.0, 0 };
Spinner spinner, spin2;
TextView TextView1;
TextView TextView2;
Double point = -1.0;
Double value = -1.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView1 = (TextView) findViewById(R.id.gradePoints);
TextView2 = (TextView) findViewById(R.id.gradeValue);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, grades);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter1);
spinner.setOnItemSelectedListener(onItemSelectedListener1);
spin2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, credits);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin2.setAdapter(adapter2);
spin2.setOnItemSelectedListener(this);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
point = points1[position];
TextView1.setText(String.valueOf(point));
if ( value != -1.0 ) {
double res = (double) point * value;
TextView2.setText(String.valueOf(res));
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
public void onItemSelected(AdapterView<?> parent, View v, int position, long id ){
Toast.makeText(this, "Your choice :" + credits[position],Toast.LENGTH_SHORT).show();
String valueStr = credits[position];
value = Double.parseDouble(valueStr);
if ( point != -1.0 ) {
double res = (double) point * value;
TextView2.setText(String.valueOf(res));
}
}
public void onNothingSelected(AdapterView<?> parent){
Toast.makeText(this, "Choose grades :", Toast.LENGTH_SHORT).show();
}
}
Hope this will work!
You can try making your selected values member variables then changing the value of the textview each time it's selected:
public class MainActivity extends AppCompatActivity{
int selectedCredit = 0;
double selectedPoints = 0;
#Override
public void onCreate(Bundle savedInstanceState){
int[] credits ={1,2,3,4};
double[] points = {4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 1.0, 0 };
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
selectedCredit = credits[position];
double value = selectedCredit * selectedPoints;
textView.setText("The calculated value is " + value);
}
#Override
public void onNothingSelected(AdapterView<?> parent){}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
selectedPoints = points[position];
double value = selectedCredit * selectedPoints;
textView.setText("The calculated value is " + value);
}
#Override
public void onNothingSelected(AdapterView<?> parent){}
});
}
}
I have given a solution according to what I understood from your question. Hope this helps. :)
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] grades ={"A","B+","B","C+","C", "D+", "D", "E"};
String[] credits ={"1","2","3","4"};
double [] points1 = {4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 1.0, 0 };
Spinner spinner;
TextView TextView1;
TextView TextView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView1 = (TextView) findViewById(R.id.gradePoints);
TextView2 = (TextView) findViewById(R.id.gradeValue);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, grades);
spinner.setAdapter(adapter1);
spinner.setOnItemSelectedListener(onItemSelectedListener1);
Spinner spin2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, credits);
spin2.setAdapter(adapter2);
spin2.setOnItemSelectedListener(this);
}
spinner.OnItemSelectedListener onItemSelectedListener1 = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String s1 = spinner.getSelectedItem().toString();
TextView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
spin2.OnItemSelectedListener onItemSelectedListener1 = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String s1 = spinner.getSelectedItem().toString();
Double gradePoint = 0.0;
if(s1.equals("A")){
gradePoint = 4.0;
}
else if(s1.equals("B+")){
gradePoint = 3.5;
}
else if(s1.equals("B")){
gradePoint = 3.0;
}
else if(s1.equals("C+")){
gradePoint = 2.5;
}
else if(s1.equals("c")){
gradePoint = 2.0;
}
else if(s1.equals("D+")){
gradePoint = 1.5;
}
else if(s1.equals("D")){
gradePoint = 1.0;
}
else if(s1.equals("E")){
gradePoint = 0;
}
int courseCredit = Integer.parseInt(spin2.getSelectedItem().toString());
double result = gradePoint*courseCredit;
TextView2.setText(String.valueOf(result));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
public void onItemSelected(AdapterView<?> parent, View v, int position, long id ){
Spinner spin = (Spinner)parent;
Spinner spin2 = (Spinner)parent;
if(spin.getId() == R.id.spinner)
{
Toast.makeText(this, "Your choice :" + grades[position],Toast.LENGTH_SHORT).show();
}
if(spin2.getId() == R.id.spinner2)
{
Toast.makeText(this, "Your choice :" + credits[position],Toast.LENGTH_SHORT).show();
}
}
public void onNothingSelected(AdapterView<?> parent){
Toast.makeText(this, "Choose grades :", Toast.LENGTH_SHORT).show();
}
}
I have a ListView with dynamically added TextViews and how do I get all TextView objects of the ListView in a String-Array ?
For testing I would like to display the whole String-Array in my Toast in the onItemClickmethod
onCreate:
final ListView sessionLv = (ListView) findViewById(R.id.session_list);
sessionLv.setAdapter(sessionAdapter);
sessionLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView c = (TextView) view.findViewById(R.id.stepTime);
String playerChanged = c.getText().toString();
Toast toast = Toast.makeText(getApplicationContext(),
playerChanged +" wurde angeklickt!",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
});
The adapter for the dynamically added TextView objects in my ListView
class SessionItemAdapter extends ArrayAdapter<Map> {
ArrayList<Map> values;
Context context;
SessionItemAdapter(Context context, ArrayList<Map> values) {
super(context, R.layout.session_list_layout_row, values);
this.values = values;
this.context = context;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.session_list_layout_row, parent, false);
TextView tv = (TextView) rowView.findViewById(R.id.stepTime);
final int rowId = (Integer) values.get(position).get("id");
int beepStringId = getResources().getIdentifier("exercise_typ_" + values.get(position).get("type"), "string", getPackageName());
rowView.setTag(rowId);
tv.setText(getResources().getString(beepStringId));
ImageButton deleteSession = (ImageButton) rowView.findViewById(R.id.session_item_del);
deleteSession.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*if (!startStopToggle.isChecked()) {*/
sessionAdapter.remove(values.get(position));
sessionAdapter.notifyDataSetChanged();
}
});
return rowView;
}
Hope this will help,
//in your item click
sessionLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SessionItemAdapter adapter = (SessionItemAdapter) parent.getAdapter();
List<String> allPlayers = adapter.getAllPlayers();
// Log your list or whatever you want to do with it
Log.i(TAG, "allPlayers: " + allPlayers.toString());
}
});
//in your adapter getAllPlayers() would be something like this
public List<String> getAllPlayers(){
List<String> list=new ArrayList<String>();
for (Map item : values) {
int beepStringId = context.getResources().getIdentifier("exercise_typ_"
+ item.get("type"), "string", context.getPackageName());
String str = context.getResources().getString(beepStringId);
list.add(str);
}
return list;
}
I am using ArrayAdapter with android.R.layout.simple_list_item_multiple_choice for my list view. I have an onItemClick() handler for the list view that launches an activity which displays the selected item in detail.
I would like this activity launched only when the click happens outside the checkbox. And when the checkbox is clicked on, I want the checkbox status toggled and NOT launch the detail view activity. Currently, both happen always when clicked on anywhere in the list, which is not desired.
Is it possible? Or should I use a custom adapter and add a checkbox and onclick handler?
You can use custom Adapter class for this, and code that use custom adapter is
For ref check here
public class PlanetsActivity extends Activity {
private ListView mainListView ;
private Planet[] planets ;
private ArrayAdapter<Planet> listAdapter ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Find the ListView resource.
mainListView = (ListView) findViewById( R.id.mainListView );
// When item is tapped, toggle checked properties of CheckBox and Planet.
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick( AdapterView<?> parent, View item,
int position, long id) {
Planet planet = listAdapter.getItem( position );
planet.toggleChecked();
PlanetViewHolder viewHolder = (PlanetViewHolder) item.getTag();
viewHolder.getCheckBox().setChecked( planet.isChecked() );
}
});
// Create and populate planets.
planets = (Planet[]) getLastNonConfigurationInstance() ;
if ( planets == null ) {
planets = new Planet[] {
new Planet("Mercury"), new Planet("Venus"), new Planet("Earth"),
new Planet("Mars"), new Planet("Jupiter"), new Planet("Saturn"),
new Planet("Uranus"), new Planet("Neptune"), new Planet("Ceres"),
new Planet("Pluto"), new Planet("Haumea"), new Planet("Makemake"),
new Planet("Eris")
};
}
ArrayList<Planet> planetList = new ArrayList<Planet>();
planetList.addAll( Arrays.asList(planets) );
// Set our custom array adapter as the ListView's adapter.
listAdapter = new PlanetArrayAdapter(this, planetList);
mainListView.setAdapter( listAdapter );
}
/** Holds planet data. */
private static class Planet {
private String name = "" ;
private boolean checked = false ;
public Planet() {}
public Planet( String name ) {
this.name = name ;
}
public Planet( String name, boolean checked ) {
this.name = name ;
this.checked = checked ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String toString() {
return name ;
}
public void toggleChecked() {
checked = !checked ;
}
}
/** Holds child views for one row. */
private static class PlanetViewHolder {
private CheckBox checkBox ;
private TextView textView ;
public PlanetViewHolder() {}
public PlanetViewHolder( TextView textView, CheckBox checkBox ) {
this.checkBox = checkBox ;
this.textView = textView ;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
public TextView getTextView() {
return textView;
}
public void setTextView(TextView textView) {
this.textView = textView;
}
}
/** Custom adapter for displaying an array of Planet objects. */
private static class PlanetArrayAdapter extends ArrayAdapter<Planet> {
private LayoutInflater inflater;
public PlanetArrayAdapter( Context context, List<Planet> planetList ) {
super( context, R.layout.simplerow, R.id.rowTextView, planetList );
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from(context) ;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Planet to display
Planet planet = (Planet) this.getItem( position );
// The child views in each row.
CheckBox checkBox ;
TextView textView ;
// Create a new row view
if ( convertView == null ) {
convertView = inflater.inflate(R.layout.simplerow, null);
// Find the child views.
textView = (TextView) convertView.findViewById( R.id.rowTextView );
checkBox = (CheckBox) convertView.findViewById( R.id.CheckBox01 );
// Optimization: Tag the row with it's child views, so we don't have to
// call findViewById() later when we reuse the row.
convertView.setTag( new PlanetViewHolder(textView,checkBox) );
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
Planet planet = (Planet) cb.getTag();
planet.setChecked( cb.isChecked() );
}
});
}
// Reuse existing row view
else {
// Because we use a ViewHolder, we avoid having to call findViewById().
PlanetViewHolder viewHolder = (PlanetViewHolder) convertView.getTag();
checkBox = viewHolder.getCheckBox() ;
textView = viewHolder.getTextView() ;
}
// Tag the CheckBox with the Planet it is displaying, so that we can
// access the planet in onClick() when the CheckBox is toggled.
checkBox.setTag( planet );
// Display planet data
checkBox.setChecked( planet.isChecked() );
textView.setText( planet.getName() );
return convertView;
}
}
public Object onRetainNonConfigurationInstance() {
return planets ;
}
}
you can do like this
public class MainActivity extends ActionBarActivity implements OnClickListener {
Button mbtn_submit;
ListView mlistview;
List<String> namesList;
ArrayAdapter<String> adapter;
String names[] = { "Divya", "Kavya", "Janu", "Anu", "Sneha", "Vistnu",
"Ravi", "Anil" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mlistview = (ListView) findViewById(R.id.listview);
mbtn_submit = (Button) findViewById(R.id.btn_submit);
namesList = new ArrayList<String>();
for (int i = 0; i < names.length; i++) {
namesList.add(names[i]);
}
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_multiple_choice, namesList);
mlistview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mlistview.setAdapter(adapter);
mbtn_submit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
SparseBooleanArray checked = mlistview.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
}
String[] selectedItemsArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
selectedItemsArr[i] = selectedItems.get(i);
}
Intent intent = new Intent(MainActivity.this,
SelectedListActivity.class);
Bundle bundle = new Bundle();
bundle.putStringArray("selectedItems", selectedItemsArr);
intent.putExtras(bundle);
startActivity(intent);
}
}
and selectedList
public class SelectedListActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_list);
Bundle bundle = getIntent().getExtras();
String[] resultArr = bundle.getStringArray("selectedItems");
ListView lv = (ListView) findViewById(R.id.selectedList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, resultArr);
lv.setAdapter(adapter);
}
}
I have got a main extending adapter which adds rows when user clicks on a button. In the adapter, I got a remove item button and a checkbox. How do I remove the item from the list?
public class main extends Activity{
ArrayList<String> noteList = new ArrayList<String>();
FancyAdapter aa = null;
Button calculate;
EditText result;
String total;
String name;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.spinner_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
ListView myListView = (ListView)findViewById(R.id.noteList);
aa = new FancyAdapter();
final EditText price = (EditText)findViewById(R.id.price);
final EditText name1 = (EditText)findViewById(R.id.name);
myListView.setAdapter(aa);
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
}
});
Button btnSimple = (Button)findViewById(R.id.btnSimple);
btnSimple.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
try
{
double totalPrice = Double.parseDouble(price.getText().toString());
int position = spinner.getSelectedItemPosition();
name = name1.getText().toString();
if(position == 0)
{
totalPrice = totalPrice * 1.07;
total = String.valueOf(totalPrice);
System.out.println(total);
}
else
{
totalPrice = (totalPrice * 1.1)*1.07;
total = String.valueOf(totalPrice);
System.out.println(total);
}
String wholeString = name + ":$" +total;
noteList.add(0, wholeString);
System.out.println(total);
name1.setText("");
price.setText("");
aa.notifyDataSetChanged();
}
catch (Exception e)
{
}
}
});
}
class FancyAdapter extends ArrayAdapter<String>
{
Button calculate;
EditText price;
EditText result;
FancyAdapter()
{
super(main.this, android.R.layout.simple_list_item_1, noteList);
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if(row == null)
{
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.custom_list_item, null);
}
StringTokenizer tokens = new StringTokenizer(noteList.get(position), ":");
String first = tokens.nextToken();
String second = tokens.nextToken();
row.getTag();
((TextView)row.findViewById(R.id.nametv)).setText(first);
((EditText)row.findViewById(R.id.result)).setText(second);
Button deleteButton = (Button) row.findViewById(R.id.button);
deleteButton.setTag(position);
deleteButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
}
}
);
return (row);
}
}
}
remove list item, and invoke notifyDataSetChanged();
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if(row == null)
{
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.custom_list_item, null);
}
StringTokenizer tokens = new StringTokenizer(noteList.get(position), ":");
String first = tokens.nextToken();
String second = tokens.nextToken();
row.getTag();
((TextView)row.findViewById(R.id.nametv)).setText(first);
((EditText)row.findViewById(R.id.result)).setText(second);
Button deleteButton = (Button) row.findViewById(R.id.button);
deleteButton.setTag(position);
deleteButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
noteList.remove(position);
notifyDataSetChanged();
}
}
);
return (row);
}
Remove the item from the arraylist using
noteList.remove(itemIndex);
and then call
aa.notifyDataSetChanged();