I am using RadioGroup as a row Item inside listview. RadioGroup has 5 radio buttons and I have like 1000 rows. I am not able to mange state of radio buttons.I have tried Map for storing position and checked state. I have even tried making Class and saving checked state and radio button id with setTag() & getTag(). No luck yet. Any suggestions?
Code
Adapter class
package com.example.adapters;
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.R;
import com.example.models.AnswerStateModel;
public class AnswerKeyAdapter extends ArrayAdapter<AnswerStateModel> {
private Activity activity;
private List<AnswerStateModel> test;
Toast t = null;
public AnswerKeyAdapter(Activity activity, List<AnswerStateModel> temp) {
super(activity, R.layout.row_item_answer_key, temp);
this.activity = activity;
this.test = temp;
}
#Override
public int getCount() {
return test.size();
}
#Override
public AnswerStateModel getItem(int position) {
return test.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int currentPosition=position;
View view=null;
if (convertView == null) {
final ViewHolder holder = new ViewHolder();
view = LayoutInflater.from(activity).inflate(
R.layout.row_item_answer_key, parent,false);
holder.lblAnswerId = (TextView) view.findViewById(R.id.lblAnswerId);
holder.rdGroup = (RadioGroup)view.findViewById(R.id.rdGroup);
holder.btnA = (RadioButton) view.findViewById(R.id.btnA);
holder.btnB = (RadioButton) view.findViewById(R.id.btnB);
holder.btnC = (RadioButton) view.findViewById(R.id.btnC);
holder.btnD = (RadioButton) view.findViewById(R.id.btnD);
holder.btnE = (RadioButton) view.findViewById(R.id.btnE);
holder.btnWhat = (Button) view.findViewById(R.id.btnWhat);
view.setTag(holder);
holder.rdGroup.setTag(test.get(position));
holder.rdGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group,
int checkedId) {
AnswerStateModel model=(AnswerStateModel) holder.rdGroup.getTag();
switch (checkedId) {
case R.id.btnA:
model.setChecked(holder.btnA.isChecked());
model.setBtnId(holder.btnA.getId());
break;
case R.id.btnB:
model.setChecked(holder.btnB.isChecked());
model.setBtnId(holder.btnB.getId());
break;
case R.id.btnC:
model.setChecked(holder.btnC.isChecked());
model.setBtnId(holder.btnC.getId());
break;
case R.id.btnD:
model.setChecked(holder.btnD.isChecked());
model.setBtnId(holder.btnD.getId());
break;
case R.id.btnE:
model.setChecked(holder.btnE.isChecked());
model.setBtnId(holder.btnE.getId());
break;
default:
break;
}
}
});
} else{
view=convertView;
((ViewHolder) view.getTag()).rdGroup.setTag(test.get(position));
}
final ViewHolder holder = (ViewHolder) view.getTag();
AnswerStateModel model=(AnswerStateModel)getItem(currentPosition);
holder.btnA.setChecked(false);
holder.btnB.setChecked(false);
holder.btnC.setChecked(false);
holder.btnD.setChecked(false);
holder.btnE.setChecked(false);
switch (model.getBtnId()) {
case R.id.btnA:
holder.btnA.setChecked(test.get(position).isChecked());
break;
case R.id.btnB:
holder.btnB.setChecked(test.get(position).isChecked());
break;
case R.id.btnC:
holder.btnC.setChecked(test.get(position).isChecked());
break;
case R.id.btnD:
holder.btnD.setChecked(test.get(position).isChecked());
break;
case R.id.btnE:
holder.btnE.setChecked(test.get(position).isChecked());
break;
default:
break;
}
holder.lblAnswerId.setText(position+1+"");
holder.btnWhat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v.isSelected())
v.setSelected(false);
else
v.setSelected(true);
}
});
return view;
}
private static class ViewHolder {
private TextView lblAnswerId;
private RadioButton btnA;
private RadioButton btnB;
private RadioButton btnC;
private RadioButton btnD;
private RadioButton btnE;
private RadioGroup rdGroup;
private Button btnWhat;
}
void showToast(String text) {
if (t != null)
t.cancel();
t = Toast.makeText(activity, text, Toast.LENGTH_SHORT);
t.show();
}
}
Pojo class
package com.example.models;
public class AnswerStateModel {
private boolean isChecked=false;
private int btnId=0;
private int currentPosition=0;
private String correctAns="";
private int btnPosition=0;
public int getBtnPosition() {
return btnPosition;
}
public void setBtnPosition(int btnPosition) {
this.btnPosition = btnPosition;
}
public String getCorrectAns() {
return correctAns;
}
public void setCorrectAns(String correctAns) {
this.correctAns = correctAns;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public int getBtnId() {
return btnId;
}
public void setBtnId(int btnId) {
this.btnId = btnId;
}
public int getCurrentPosition() {
return currentPosition;
}
public void setCurrentPosition(int currentPosition) {
this.currentPosition = currentPosition;
}
}
Solved it! Used SparseIntArray
Here is the complete code.
/**
*
*/
package com.example.adapters;
import java.util.ArrayList;
import android.app.Activity;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.R;
import com.example.models.AnswerStateModel;
import com.example.utils.Config;
public class AnswerKeyAdapter extends ArrayAdapter<AnswerStateModel> {
private Activity activity;
private ArrayList<AnswerStateModel> mAnswerList;
Toast t = null;
private SparseIntArray mSpCheckedState=new SparseIntArray();
public AnswerKeyAdapter(Activity activity, ArrayList<AnswerStateModel> mAnswerList) {
super(activity, R.layout.row_item_answer_key, mAnswerList);
this.activity = activity;
this.mAnswerList = mAnswerList;
}
#Override
public int getCount() {
return mAnswerList.size();
}
#Override
public AnswerStateModel getItem(int position) {
return mAnswerList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(activity).inflate(
R.layout.row_item_answer_key, parent, false);
holder.lblAnswerId = (TextView) convertView.findViewById(R.id.lblAnswerId);
holder.rdGroup = (RadioGroup) convertView.findViewById(R.id.rdGroup);
holder.btnA = (RadioButton) convertView.findViewById(R.id.btnA);
holder.btnB = (RadioButton) convertView.findViewById(R.id.btnB);
holder.btnC = (RadioButton) convertView.findViewById(R.id.btnC);
holder.btnD = (RadioButton) convertView.findViewById(R.id.btnD);
holder.btnE = (RadioButton) convertView.findViewById(R.id.btnE);
holder.btnWhat = (Button) convertView.findViewById(R.id.btnWhat);
convertView.setTag(holder);
} else {
holder=(ViewHolder)convertView.getTag();
}
holder.rdGroup.setOnCheckedChangeListener(null);
holder.rdGroup.clearCheck();
Config.error("Spars "+mSpCheckedState.get(position));
if(mSpCheckedState.indexOfKey(position)>-1){
holder.rdGroup.check(mSpCheckedState.get(position));
}else{
holder.rdGroup.clearCheck();
}
holder.rdGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId>-1){
mSpCheckedState.put(position, checkedId);
}else{
if(mSpCheckedState.indexOfKey(position)>-1)
mSpCheckedState.removeAt(mSpCheckedState.indexOfKey(position));
}
}
});
Config.error("Current Position " + position);
holder.lblAnswerId.setText(position + 1 + "");
holder.btnWhat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v.isSelected())
v.setSelected(false);
else
v.setSelected(true);
}
});
return convertView;
}
private static class ViewHolder {
private TextView lblAnswerId;
private RadioButton btnA;
private RadioButton btnB;
private RadioButton btnC;
private RadioButton btnD;
private RadioButton btnE;
private RadioGroup rdGroup;
private Button btnWhat;
}
void showToast(String text) {
if (t != null)
t.cancel();
t = Toast.makeText(activity, text, Toast.LENGTH_SHORT);
t.show();
}
}
Related
In my BaseAdpater I'm setting the visibility of a view to GONE in a row after some operation. All operation is fine but view remains visible in background while lower views are move up until i touch the screen. It means listview is updating the views and releasing the space on setting visibility to GONE but view is still visible in background. What could be the issue?
Code:
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.iu.foodbucket.BaseActivity;
import com.iu.foodbucket.R;
import com.iu.foodbucket.database.MyDataSource;
import com.iu.foodbucket.fragments.CartFragment;
import com.iu.foodbucket.models.Cart;
import com.iu.foodbucket.utils.AppGlobal;
import java.util.List;
public class CartAdapter extends BaseAdapter {
Fragment context;
List<Cart> data;
MyDataSource myDataSource;
boolean isOldOrder;
public CartAdapter(Fragment ctx, List<Cart> data, boolean orderStatus) {
this.context = ctx;
this.data = data;
this.isOldOrder = orderStatus;
myDataSource = new MyDataSource(ctx.getActivity());
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row_cart, parent, false);
holder.title_tv = (TextView) convertView.findViewById(R.id.title_tv);
holder.quantity_tv = (TextView) convertView.findViewById(R.id.quantity_tv);
holder.price_tv = (TextView) convertView.findViewById(R.id.price_tv);
holder.edit_iv = (ImageView) convertView.findViewById(R.id.edit_iv);
holder.thumbnail_iv = (ImageView) convertView.findViewById(R.id.thumbnail_iv);
holder.editPanel = (LinearLayout) convertView.findViewById(R.id.editPanel);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title_tv.setText(data.get(position).getMenu().getTitle());
holder.quantity_tv.setText(context.getString(R.string.quantity_abbr) + " " + data.get(position).getQuantity());
if (((BaseActivity) context.getActivity()).dataPreference.getIsImageEnabled())
Glide.with(context.getActivity()).load(data.get(position).getMenu().getThumbnail()).placeholder(R.drawable.ic_tag_face).centerCrop().into(holder.thumbnail_iv);
float price = Float.parseFloat(data.get(position).getMenu().getPrice());
price = (float) AppGlobal.round(price, 2);
holder.price_tv.setText(data.get(position).getMenu().getPriceUnit() + " " + price);
final View finalConvertView = convertView;
holder.edit_iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.editPanel.getVisibility() != View.VISIBLE) {
holder.editPanel.setVisibility(View.VISIBLE);
showEditablePanel(finalConvertView, position, holder.editPanel);
} else {
holder.editPanel.setVisibility(View.GONE);
}
}
});
return convertView;
}
private void showEditablePanel(View v, final int position, final LinearLayout editPanel) {
final TextView quantity_tv = (TextView) v.findViewById(R.id.quantityUpdated_tv);
final ImageButton minus_btn = (ImageButton) v.findViewById(R.id.minus_btn);
final ImageButton plus_btn = (ImageButton) v.findViewById(R.id.plus_btn);
ImageButton update_btn = (ImageButton) v.findViewById(R.id.update_btn);
ImageButton remove_btn = (ImageButton) v.findViewById(R.id.remove_btn);
final int[] quantity = {Integer.parseInt(data.get(position).getQuantity())};
quantity_tv.setText(quantity[0] + "");
minus_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity[0]--;
updateViews(quantity[0], minus_btn, quantity_tv);
}
});
plus_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity[0]++;
updateViews(quantity[0], minus_btn, quantity_tv);
}
});
update_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isOldOrder) // update cart item in DB
myDataSource.updateCartItem(data.get(position).getMenu().getId(), quantity[0] + "");
data.get(position).setQuantity(quantity[0] + "");
editPanel.setVisibility(View.GONE);
notifyDataSetChanged();
((CartFragment) context).updateTotalValues();
}
});
remove_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deletionConfirmationDialog(position, editPanel);
}
});
}
public void deletionConfirmationDialog(final int position, final LinearLayout editPanel) {
final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(context.getActivity());
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setTitle(context.getString(R.string.title_delete));
alertDialogBuilder.setMessage(context.getString(R.string.message_confirm_deletion));
alertDialogBuilder.setPositiveButton(context.getString(R.string.title_yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (!isOldOrder) // delete cart item from DB
myDataSource.deleteCartItem(data.get(position).getMenu().getId());
editPanel.setVisibility(View.GONE);
data.remove(position);
notifyDataSetChanged();
((CartFragment) context).updateTotalValues();
}
});
alertDialogBuilder.setNegativeButton(context.getString(R.string.title_no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
}
});
android.app.AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void updateViews(int quantity, ImageButton minus_btn, TextView quantity_tv) {
if (quantity > 1) {
minus_btn.setEnabled(true);
minus_btn.setAlpha((float) 1.0);
} else {
minus_btn.setEnabled(false);
minus_btn.setAlpha((float) 0.4);
}
quantity_tv.setText(quantity + "");
}
private class ViewHolder {
TextView title_tv, quantity_tv, price_tv;
ImageView thumbnail_iv, edit_iv;
LinearLayout editPanel;
}
}
if you mean after setting visiblity gone of a row, that row remains blank and that gap is visible,the better way is to filter the adapter content by using getFilter() to display by excluding that row content and notifyadapter changed.
I referred [this][1] and [this][2] site and tried to modify it according to my own needs. Problem is I can't remove an item from the cart. I have tried everything including searching for solutions in stackoverflow and google but no luck.
Here is my CatalogActivity.java
package com.comlu.sush.shoppingcart;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import java.util.List;
public class CatalogActivity extends AppCompatActivity {
private List<Product> mProductList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());
// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false,false));
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
startActivity(productDetailsIntent);
}
});
Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
}
ShoppingCartHelper.java
package com.comlu.sush.shoppingcart;
import android.content.res.Resources;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
public class ShoppingCartHelper {
public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
private static List<Product> catalog;
private static Map<Product, ShoppingCartEntry> cartMap = new HashMap<Product, ShoppingCartEntry>();
public static List<Product> getCatalog(Resources res){
if(catalog == null) {
catalog = new Vector<Product>();
catalog.add(new Product("Dead or Alive", res
.getDrawable(R.drawable.first),
"Dead or Alive by Tom Clancy with Grant Blackwood", 29.99));
catalog.add(new Product("Switch", res
.getDrawable(R.drawable.second),
"Switch by Chip Heath and Dan Heath", 24.99));
catalog.add(new Product("Watchmen", res
.getDrawable(R.drawable.third),
"Watchmen by Alan Moore and Dave Gibbons", 14.99));
}
return catalog;
}
public static void setQuantity(Product product, int quantity) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
// If the quantity is zero or less, remove the products
if(quantity <= 0) {
if(curEntry != null)
removeProduct(product);
return;
}
// If a current cart entry doesn't exist, create one
if(curEntry == null) {
curEntry = new ShoppingCartEntry(product, quantity);
cartMap.put(product, curEntry);
return;
}
// Update the quantity
curEntry.setQuantity(quantity);
}
public static int getProductQuantity(Product product) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
if(curEntry != null)
return curEntry.getQuantity();
return 0;
}
public static void removeProduct(Product product) {
cartMap.remove(product);
}
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
return cartList;
}
}
ShoppingCartActiity.java
package com.comlu.sush.shoppingcart;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import java.util.List;
public class ShoppingCartActivity extends AppCompatActivity {
private List<Product> mCartList;
private ProductAdapter mProductAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
mCartList = ShoppingCartHelper.getCartList();
// Make sure to clear the selections
for(int i=0; i<mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(), true,true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mProductAdapter.toggleSelection(position);
}
});
removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProductAdapter.removeSelected();
}
});
}
#Override
protected void onResume() {
super.onResume();
// Refresh the data
if(mProductAdapter != null) {
mProductAdapter.notifyDataSetChanged();
}
}
}
ProductDetailsActivity.java
package com.comlu.sush.shoppingcart;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class ProductDetailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
final int result=0;
List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());
int productIndex = getIntent().getExtras().getInt(
ShoppingCartHelper.PRODUCT_INDEX);
final Product selectedProduct = catalog.get(productIndex);
// Set the proper image and text
ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
productImageView.setImageDrawable(selectedProduct.productImage);
TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
productTitleTextView.setText(selectedProduct.title);
TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
productDetailsTextView.setText(selectedProduct.description);
// Update the current quantity in the cart
TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
textViewCurrentQuantity.setText("Currently in Cart: "
+ ShoppingCartHelper.getProductQuantity(selectedProduct));
// Save a reference to the quantity edit text
final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);
Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
addToCartButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Check to see that a valid quantity was entered
int quantity = 0;
try {
quantity = Integer.parseInt(editTextQuantity.getText()
.toString());
if (quantity < 0) {
Toast.makeText(getBaseContext(),
"Please enter a quantity of 0 or higher",
Toast.LENGTH_SHORT).show();
return;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),
"Please enter a numeric quantity",
Toast.LENGTH_SHORT).show();
return;
}
// If we make it here, a valid quantity was entered
ShoppingCartHelper.setQuantity(selectedProduct, quantity);
// Close the activity
finish();
}
});
}
}
ProductAdapter.java
package com.comlu.sush.shoppingcart;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class ProductAdapter extends BaseAdapter {
private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
private boolean mShowCheckbox;
public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity, boolean showCheckbox) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
mShowCheckbox = showCheckbox;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
item = new ViewItem();
item.productImageView = (ImageView) convertView
.findViewById(R.id.ImageViewItem);
item.productTitle = (TextView) convertView
.findViewById(R.id.TextViewItem);
item.productQuantity = (TextView) convertView
.findViewById(R.id.textViewQuantity);
item.productCheckbox = (CheckBox) convertView.findViewById(R.id.CheckBoxSelected);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
Product curProduct = mProductList.get(position);
item.productImageView.setImageDrawable(curProduct.productImage);
item.productTitle.setText(curProduct.title);
if(!mShowCheckbox) {
item.productCheckbox.setVisibility(View.GONE);
} else {
if(curProduct.selected == true)
item.productCheckbox.setChecked(true);
else
item.productCheckbox.setChecked(false);
}
// Show the quantity in the cart or not
if (mShowQuantity) {
item.productQuantity.setText("Quantity: "
+ ShoppingCartHelper.getProductQuantity(curProduct));
} else {
// Hid the view
item.productQuantity.setVisibility(View.GONE);
}
return convertView;
}
public void toggleSelection(int position) {
Product selectedProduct = (Product) getItem(position);
if(selectedProduct.selected) { // no need to check " == true"
selectedProduct.selected = false;
}
else {
selectedProduct.selected = true;
}
notifyDataSetInvalidated();
}
public void removeSelected() {
for(int i=mProductList.size()-1; i>=0; i--) {
if(mProductList.get(i).selected) {
mProductList.remove(i);
}
}
notifyDataSetChanged();
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
CheckBox productCheckbox;
}
}
You should move data manipulation to the adapter, and design-wise it would make sense and might also fix the problem you're telling us.
Write this method in your ProductAdapter:
public void removeSelected() {
for(int i = mProductList.size()-1; i >= 0; i--) {
if(mProductList.get(i).selected) {
mProductList.remove(i);
}
}
notifyDataSetChanged();
}
Update your OnClickListener (in your ShoppingCartActiity of course):
removeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mProductAdapter.removeSelected();
}
});
Edit
I noticed that you aren't applying OOP's concept of encapsulation here. That is, ShoppingCartActiity shouldn't be making changes to the data which belongs to your adapter.
So, just create public methods inside the ProductAdapter for item for selection, etc and call them from ShoppingCartActiity as needed.
Copy this method in your ProductAdapter:
public void toggleSelection(int position) {
Product selectedProduct = (Product) getItem(position);
if(selectedProduct.selected) { // no need to check " == true"
selectedProduct.selected = false;
}
else {
selectedProduct.selected = true;
}
notifyDataSetInvalidated();
}
mProductAdapter.toggleSelection(position); will replace following code ShoppingCartActiity:
Product selectedProduct = mCartList.get(position);
if(selectedProduct.selected == true)
selectedProduct.selected = false;
else
selectedProduct.selected = true;
mProductAdapter.notifyDataSetInvalidated();
Edit2
The problem is that the ShoppingCartActiity takes items from ShoppingCartEntry on starting up, but it never writes back the changes to it when you remove items.
update your removeButton's onClick() to:
mProductAdapter.removeSelected();
if (product.selected) {
// set products which are remaining in the adapter
ShoppingCartHelper.setProducts(mProductAdapter.getProducts());
}
ShoppingCartHelper.setProducts() would replace the old data with the passed one:
public static void setProducts(ArrayList<Product> products) {
catalog = new Vector<Product>();
for (Product product : products) {
catalog.add(product);
}
}
mProductAdapter.getProducts() will just return the list of Products, like:
public List<Product> getProducts() {
return mProductList;
}
you just have to remove selected item from list, and after adapter.notifiyDataSetChanged() it will refresh the adapter.
removeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Loop through and remove all the products that are selected
// Loop backwards so that the remove works correctly
for(int i=mCartList.size()-1; i>=0; i--) {
if(mCartList.get(i).selected) {
mCartList.remove(i);
//mProductAdapter.removeSelected();
}
}
if(mProductAdapter!=null)
mProductAdapter.notifyDataSetChanged();
}
});
When i click the radio group from the first item all the
corresponding items should be selected when the check box is checked
if the check box is not checked then the corresponding items radio
button should not be checked.
if i click in between then first item radio button should be
deselect else if i click the unchecked radio button the check box
should be checked and radio button also be checked. This is what i
want to achieve in this.
My problem from the below code is when i click the first item all the items getting selected but if i click another item in between the first item is getting deselected and the button which i clicked is re positioned
TeacherAssessmentFragmentChild.java
package com.example.playit;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
#SuppressLint("NewApi")
public class TeacherAssessmentFragmentChild extends Fragment {
static Context context;
ArrayList<TeacherAssessmentFragmentChildContainer> assessmentContainer=new ArrayList<>();
View rootView ;
ListView lstassessment;
TeacherAssessmentFragmentChildListAdapter listAdapter;
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.teacher_asseessment_view_fragment_child,
container, false);
Initialize();
context = TeacherAssessmentFragment.context;
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chapter", "-1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 1 Algebra", "1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 2 Trignomentry", "-1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 3 Integration", "4"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 4 Differentiation", "3"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 5 Abacus", "2"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 6 Numbersystem", "-1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 7 Algebra", "-1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 8 Algebra", "2"));
listAdapter=new TeacherAssessmentFragmentChildListAdapter(context, 0, assessmentContainer);
lstassessment.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
return rootView;
}
public void Initialize() {
lstassessment=(ListView) rootView.findViewById(R.id.teacher_assessment_view_fragment_clild_assessment_list);
}
}
TeacherAssessmentFragmentChildContainer.java
package com.example.playit;
public class TeacherAssessmentFragmentChildContainer {
String chapterName,moduleSelected;
Boolean ismoduleActive;
public TeacherAssessmentFragmentChildContainer(String chapterName,
String moduleSelected) {
super();
this.chapterName = chapterName;
this.moduleSelected = moduleSelected;
if(moduleSelected.equalsIgnoreCase("-1"))
ismoduleActive=false;
else
ismoduleActive=true;
}
public Boolean getIsmoduleActive() {
return ismoduleActive;
}
public void setIsmoduleActive(Boolean ismoduleActive) {
this.ismoduleActive = ismoduleActive;
}
public String getChapterName() {
return chapterName;
}
public String getModuleSelected() {
return moduleSelected;
}
public void setModuleSelected(String moduleSelected) {
this.moduleSelected = moduleSelected;
}
}
TeacherAssessmentFragmentChildListAdapter
package com.example.playit;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
#SuppressLint("NewApi")
public class TeacherAssessmentFragmentChildListAdapter extends
ArrayAdapter<TeacherAssessmentFragmentChildContainer> {
static Context context;
static ArrayList<TeacherAssessmentFragmentChildContainer> container = new ArrayList<>();
ViewHolder holder;
static int checkBoxCount = 0, radioCount = 0, selectedPosition = -1;
public TeacherAssessmentFragmentChildListAdapter(Context context,
int resource,
ArrayList<TeacherAssessmentFragmentChildContainer> container) {
super(context, resource, container);
this.context = context;
this.container = container;
}
#Override
public int getViewTypeCount() {
// Count=Size of ArrayList.
return container.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return super.getCount();
}
public class ViewHolder {
TextView txvchapterName;
CheckBox ckbselectName;
RadioGroup rgassessment;
RadioButton assessment1, assessment2, assessment3, assessment4,
assessment5;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// System.out.println("getview:" + position + " " + convertView);
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater
.inflate(
R.layout.teacher_assessment_view_fragment_child_list_adapter,
parent, false);
holder = new ViewHolder();
holder.txvchapterName = (TextView) row
.findViewById(R.id.teacher_view_fragment_child_list_adapter_chapter);
holder.ckbselectName = (CheckBox) row
.findViewById(R.id.teacher_view_fragment_child_list_adapter_select);
holder.rgassessment = (RadioGroup) row
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment_group);
holder.assessment1 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment1);
holder.assessment2 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment2);
holder.assessment3 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment3);
holder.assessment4 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment4);
holder.assessment5 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment5);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
if (position == 0) {
holder.assessment1.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment2.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment3.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment4.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment5.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment1.setText("");
holder.assessment2.setText("");
holder.assessment3.setText("");
holder.assessment4.setText("");
holder.assessment5.setText("");
} else {
holder.assessment1.setButtonDrawable(android.R.color.transparent);
holder.assessment2.setButtonDrawable(android.R.color.transparent);
holder.assessment3.setButtonDrawable(android.R.color.transparent);
holder.assessment4.setButtonDrawable(android.R.color.transparent);
holder.assessment5.setButtonDrawable(android.R.color.transparent);
holder.assessment1.setText("M1");
holder.assessment2.setText("M2");
holder.assessment3.setText("M3");
holder.assessment4.setText("M4");
holder.assessment5.setText("M5");
}
holder.ckbselectName.setTag(position);
holder.rgassessment.setTag(position);
SetCheckedRbn(container.get(position).getModuleSelected());
SetCheckedChb(container.get(position).ismoduleActive);
holder.ckbselectName.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
System.out.println("selectedPosition : "+selectedPosition);
System.out.println("container.get(selectedPosition).getIsmoduleActive() : "+container.get(selectedPosition).getIsmoduleActive());
if(selectedPosition==0){
for(int i=0;i<container.size();i++){
if(!container.get(i).getIsmoduleActive()){
container.get(i).setIsmoduleActive(true);
container.get(i).setModuleSelected("0");
}
else {
container.get(i).setIsmoduleActive(false);
container.get(i).setModuleSelected("-1");
}
}
}
else {
if(!container.get(selectedPosition).getIsmoduleActive()){
container.get(selectedPosition).setIsmoduleActive(true);
container.get(selectedPosition).setModuleSelected("0");
}
else {
container.get(selectedPosition).setIsmoduleActive(false);
container.get(selectedPosition).setModuleSelected("-1");
}
}
System.out.println("container.get(selectedPosition).getIsmoduleActive() : "+container.get(selectedPosition).getIsmoduleActive());
notifyDataSetChanged();
}
});
holder.txvchapterName.setText(container.get(position).getChapterName());
holder.rgassessment
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
selectedPosition = (Integer) group.getTag();
View radioButtonView = group.findViewById(checkedId);
RadioButton checkedRadioButton = (RadioButton)group.findViewById(checkedId);
int idx = group.indexOfChild(radioButtonView);
if (selectedPosition == 0 && checkedRadioButton.isChecked() ) {
for (int i = 0; i < container.size(); i++) {
if (container.get(i).getIsmoduleActive() || i==0 ){
container.get(i).setModuleSelected("" + idx);
}
else if(i!=0){
container.get(i).setModuleSelected("-1");
container.get(i).setIsmoduleActive(false);
}
}
}
else if(selectedPosition !=0){
container.get(selectedPosition).setIsmoduleActive(
true);
container.get(selectedPosition).setModuleSelected(
"" + idx);
}
checkrb();
}
});
return row;
}
public void SetCheckedRbn(String str) {
switch (str) {
case "0":
holder.assessment1.setChecked(true);
break;
case "1":
holder.assessment2.setChecked(true);
break;
case "2":
holder.assessment3.setChecked(true);
break;
case "3":
holder.assessment4.setChecked(true);
break;
case "4":
holder.assessment5.setChecked(true);
break;
default:
holder.assessment1.setChecked(false);
holder.assessment2.setChecked(false);
holder.assessment3.setChecked(false);
holder.assessment4.setChecked(false);
holder.assessment5.setChecked(false);
break;
}
}
public void SetCheckedChb(Boolean isactive) {
if (isactive)
holder.ckbselectName.setChecked(true);
else
holder.ckbselectName.setChecked(false);
}
public void checkrb() {
int rbcount=0,chcount=0;
String str="";
for(int i=0;i<container.size();i++) {
str=container.get(i).getModuleSelected();
if(str!="-1"){
break;
}
}
for(int i=1;i<container.size() && str!="";i++) {
if(str.equals(container.get(i).getModuleSelected()) && container.get(i).getIsmoduleActive()){
rbcount++;
str=container.get(i).getModuleSelected();
}
if(container.get(i).getIsmoduleActive())
chcount++;
}
if(rbcount!=chcount)
container.get(0).setModuleSelected("-1");
else
container.get(0).setModuleSelected(str);
if(rbcount==container.size())
container.get(0).setIsmoduleActive(true);
else
container.get(0).setIsmoduleActive(false);
notifyDataSetChanged();
}
public void checkchb() {
int chcount=0;
for(int i=0;i<container.size();i++) {
if(container.get(i).getIsmoduleActive())
chcount++;
}
if(chcount==(container.size()-1)){
container.get(0).setIsmoduleActive(true);
}
else
container.get(0).setIsmoduleActive(false);
notifyDataSetChanged();
}
}
I am facing the problem to view the checked item of the listview and after if user want to modify the checked item to other item then he can modify check-box. After modify he again want to view what i checked in list. My code not working correct to view what he checked. Please help and it much appreciate
Here is my adapter class:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.kns.model.CategoryModel;
import com.sunil.selectmutiple.R;
public class CategoryAdapter extends BaseAdapter{
private final List<CategoryModel> list;
private final Activity context;
private LayoutInflater mInflater=null;
ArrayList<CategoryModel> list1 = new ArrayList<CategoryModel>();
private static final String TAG="CategoryAdapter";
String catid1;
String catid2;
String catid3;
public CategoryAdapter(Activity context, List<CategoryModel> list, String catid1, String catid2, String catid3) {
// super(context, R.layout.listcheck, list);
mInflater = context.getLayoutInflater();
this.context = context;
this.list = list;
this.catid1=catid1;
this.catid2=catid2;
this.catid3=catid3;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int arg0) {
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = mInflater.inflate(R.layout.cate_list_item, parent, false);
}
CategoryModel p = getProduct(position);
TextView text = (TextView) view.findViewById(R.id.textView_custname);
CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkBox1);
checkbox.setOnCheckedChangeListener(myCheckChangList);
checkbox.setTag(position);
String catid=p.getCat_id();
Log.v(TAG, "Cat id is: "+catid);
Log.v(TAG, "Cat id1 is: "+catid1);
Log.v(TAG, "Cat id2 is: "+catid2);
Log.v(TAG, "Cat id3 is: "+catid3);
if (catid1.trim().equalsIgnoreCase("0") && catid2.trim().equalsIgnoreCase("0") && catid3.trim().equalsIgnoreCase("0")) {
checkbox.setChecked(p.isIsselected());
}
else{
if (catid.trim().equalsIgnoreCase(catid1)) {
checkbox.setChecked(true);
// getProduct((Integer) checkbox.getTag()).setIsselected(true) ;
}
else if (catid.trim().equalsIgnoreCase(catid2)) {
checkbox.setChecked(true);
// getProduct((Integer) checkbox.getTag()).setIsselected(true) ;
}
else if (catid.trim().equalsIgnoreCase(catid3)) {
checkbox.setChecked(true);
// getProduct((Integer) checkbox.getTag()).setIsselected(true) ;
}
else{
checkbox.setChecked(false);
}
}
text.setText(p.getCat_name());
// checkbox.setChecked(p.isIsselected());
return view;
}
CategoryModel getProduct(int position) {
return ((CategoryModel) getItem(position));
}
public ArrayList<CategoryModel> getChecked() {
ArrayList<CategoryModel> list1 = new ArrayList<CategoryModel>();
for (CategoryModel details : list) {
if (details.isIsselected())
list1.add(details);
}
return list1;
}
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ArrayList<CategoryModel> list1=getChecked();
Log.v(TAG, "checked size is: "+list1.size());
if (isChecked) {
if (list1.size() >= 3) {
buttonView.setChecked(false);
//getProduct((Integer) buttonView.getTag()).setIsselected(isChecked) ;
Toast.makeText(context, "Please select max 3 Categories.", Toast.LENGTH_LONG).show();
}
else{
getProduct((Integer) buttonView.getTag()).setIsselected(isChecked) ;
}
}
else{
getProduct((Integer) buttonView.getTag()).setIsselected(isChecked) ;
}
}
};
}
By clicking on the item, nothing happens. Prompt where I have not correctly implemented method OnItemClickListener.
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.lessons.Lesson1;
public class Lesson extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lesson);
ListView lista = (ListView) findViewById(R.id.itemlist);
ArrayList<Manager> arraydir = new ArrayList<Manager>();
Manager manager;
Resources res = getResources();
// Вводим данные
manager = new Manager(res.getDrawable(R.drawable.lesson1), res.getString(R.string.lesson1), res.getString(R.string.lessonname1));
arraydir.add(manager);
manager = new Manager(res.getDrawable(R.drawable.lesson2), res.getString(R.string.lesson2), res.getString(R.string.lessonname2));
arraydir.add(manager);
AdapterLesson adapter = new AdapterLesson(this, arraydir);
lista.setAdapter(adapter);
lista.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) {
TextView textView = (TextView) itemClicked.findViewById(R.id.lessonname);
String strText = textView.getText().toString();
if (strText.equalsIgnoreCase(getResources().getString(R.string.lesson1))) {
// Launch the lesson1 Activity
startActivity(new Intent(Lesson.this, Lesson1.class));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Adapter
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class AdapterLesson extends BaseAdapter{
protected Activity activity;
protected ArrayList<Manager> items;
public AdapterLesson(Activity activity, ArrayList<Manager> items) {
this.activity = activity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int arg0) {
return items.get(arg0);
}
#Override
public long getItemId(int position) {
return items.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Создаем convertView для эффективности
View v = convertView;
//Связываем формат списка, который мы создали
if(convertView == null){
LayoutInflater inf = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inf.inflate(R.layout.itemlist, null);
}
// Создаем объект директивы
Manager dir = items.get(position);
//Вводим фото
ImageView foto = (ImageView) v.findViewById(R.id.foto);
foto.setImageDrawable(dir.getFoto());
//Вводим номер урока
TextView lessonnumber = (TextView) v.findViewById(R.id.lessonnumber);
lessonnumber.setText(dir.getLessonnumber());
//Вводим название урока
TextView lessonname = (TextView) v.findViewById(R.id.lessonname);
lessonname.setText(dir.getLessonname());
// Возвращаем
return v;
}
}
Manager
import android.graphics.drawable.Drawable;
public class Manager {
protected Drawable foto;
protected String lessonnumber;
protected String lessonname;
protected long id;
public Manager(Drawable foto, String lessonnumber, String lessonname) {
super();
this.foto = foto;
this.lessonnumber = lessonnumber;
this.lessonname = lessonname;
}
public Manager(Drawable foto, String lessonnumber, String lessonname, long id) {
super();
this.foto = foto;
this.lessonnumber = lessonnumber;
this.lessonname = lessonname;
this.id = id;
}
public Drawable getFoto() {
return foto;
}
public void setFoto(Drawable foto) {
this.foto = foto;
}
public String getLessonnumber() {
return lessonnumber;
}
public void setLessonnumber(String lessonnumber) {
this.lessonnumber = lessonnumber;
}
public String getLessonname() {
return lessonname;
}
public void setLessonname(String lessonname) {
this.lessonname = lessonname;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
use this code for click on listitem and go to next extivity..
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch(position){
case 0:
Intent firstIntent = new Intent(yourclass.this, firstitem.class);
startActivity(firstIntent);
break;
case 1:
Intent secondintent = new Intent(yourclass.this, seconditem.class);
startActivity(secondintent);
break;
Try This code only change get view method part
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Создаем convertView для эффективности
View v = convertView;
//Связываем формат списка, который мы создали
if(convertView == null){
LayoutInflater inf = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inf.inflate(R.layout.itemlist, null);
}
// Создаем объект директивы
Manager dir = items.get(position);
//Вводим фото
ImageView foto = (ImageView) v.findViewById(R.id.foto);
foto.setImageDrawable(dir.getFoto());
//Вводим номер урока
TextView lessonnumber = (TextView) v.findViewById(R.id.lessonnumber);
lessonnumber.setText(dir.getLessonnumber());
//Вводим название урока
TextView lessonname = (TextView) v.findViewById(R.id.lessonname);
lessonname.setText(dir.getLessonname());
v.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
Intent firstIntent = new Intent(yourclass.this, firstitem.class);
startActivity(firstIntent);
} });
// Возвращаем
return v;
}