I'm Developing an Android Application .In that Application ,I've set a list view each has One Imageview,Progressbar(InVisible) and two buttons .
plAdapter = new PlayAdapter();
lv1.setAdapter(plAdapter);
}
private static class AccessoriesViewHolder {
Button play,download;
ProgressBar pb;
}
private class PlayAdapter extends BaseAdapter {
#Override
public int getCount() {
return contactList.toArray().length;
}
#Override
public String getItem(int position) {
return a;
//return al[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
holder = null;
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.design, parent, false);
holder = new AccessoriesViewHolder();
holder.play = (Button) convertView.findViewById(R.id.btn_play);
holder.download = (Button) convertView.findViewById(R.id.btn_dwnld);
((Button) convertView.findViewById(R.id.btn_play)).setOnClickListener(mBuyButtonClickListener);
((Button) convertView.findViewById(R.id.btn_dwnld)).setOnClickListener(mBuyButtonClickListener);
((ProgressBar) convertView.findViewById(R.id.progress_bar)).setVisibility(View.INVISIBLE);
// convertView.setTag(holder);
} else
{
holder = (AccessoriesViewHolder) convertView.getTag();
}
/*
* The Android API provides the OnCheckedChangeListener interface
* and its onCheckedChanged(CompoundButton buttonView, boolean
* isChecked) method. Unfortunately, this implementation suffers
* from a big problem: you can't determine whether the checking
* state changed from code or because of a user action. As a result
* the only way we have is to prevent the CheckBox from callbacking
* our listener by temporary removing the listener.
*/
return convertView;
}
}
/**
* Quickly shows a message to the user using a {#link Toast}.
*
* #param message The message to show
*/
private void showMessage(String message) {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
private OnClickListener mBuyButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
final int position = lv1.getPositionForView(v);
// int dummy=position;
showMessage(listsong[position].toString()+"");
((ProgressBar) convertView.findViewById(R.id.progress_bar)).setVisibility(View.INVISIBLE);
}
};
protected AdapterView<ListAdapter> getListView()
{
// TODO Auto-generated method stub
return null;
}
}
If I click one of the Button in a row ., the Progress bar Must be visible in that row.
The problem is, if i click a button the progress bar on other row gets visible but not corresponding row.
Just Add an OnClickListener for the button in the getView() method in your ListView Adapter and inside the OnClickListener set the visibility of the ProgressBar
Try to change your getView method like that:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
holder = new AccessoriesViewHolder();
convertView = getLayoutInflater().inflate(R.layout.design, parent, false);
holder.play = (Button) convertView.findViewById(R.id.btn_play);
holder.download = (Button) convertView.findViewById(R.id.btn_dwnld);
((Button) convertView.findViewById(R.id.btn_play)).setOnClickListener(mBuyButtonClickListener);
((Button) convertView.findViewById(R.id.btn_dwnld)).setOnClickListener(mBuyButtonClickListener);
((ProgressBar) convertView.findViewById(R.id.progress_bar)).setVisibility(View.INVISIBLE);
return convertView;
}
Related
I have a problem using folding cell library from the RAMOTION
I have implemented everything but I am facing a problem with the list view
I have a list of planets and when user tap on let's say Jupiter the view gets unfolded and more information is visible to the user and when user tap on the same view which is seeing then the view gets folded
Problem
if the user scrolls down the list and then scroll back up and come back up to Jupiter the view remains unfolded and it is happening to all the view.
I appreciate if anyone helps me out
folding state
here
unfolding state
here
AdapterClass
#SuppressWarnings({"WeakerAccess", "unused"})
public class SolarSystemFoldingCellListAdapter extends ArrayAdapter<SolarSystemItemFoldingCell> {
private HashSet<Integer> unfoldedIndexes = new HashSet<>();
private View.OnClickListener defaultRequestBtnClickListener;
private int incomingPosition ;
public SolarSystemFoldingCellListAdapter(Context context, List<SolarSystemItemFoldingCell> objects) {
super(context, 0, objects);
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
// get item for selected view
SolarSystemItemFoldingCell solarSystemItemFoldingCell = getItem(position);
// if cell is exists - reuse it, if not - create the new one from resource
FoldingCell cell = (FoldingCell) convertView;
final ViewHolder viewHolder;
if (cell == null) {
viewHolder = new ViewHolder();
LayoutInflater vi = LayoutInflater.from(getContext());
cell = (FoldingCell) vi.inflate(R.layout.solar_system_folding_cell, parent, false);
// binding view parts to view holder
viewHolder.foldingCell = cell.findViewById(R.id.folding_cell);
viewHolder.relativeLayoutFolded = cell.findViewById(R.id.relativeLayoutFolded);
viewHolder.linearLayoutFolded = cell.findViewById(R.id.linearLayoutFolded);
viewHolder.planetOrStarNameFolded = cell.findViewById(R.id.planetOrStarNameFolded);
viewHolder.mass = cell.findViewById(R.id.mass);
viewHolder.actualMass = cell.findViewById(R.id.actualMass);
viewHolder.distance = cell.findViewById(R.id.distance);
viewHolder.actualDistance = cell.findViewById(R.id.actualDistance);
viewHolder.diameter = cell.findViewById(R.id.diameter);
viewHolder.actualDiameter = cell.findViewById(R.id.actualDiameter);
viewHolder.speed = cell.findViewById(R.id.speed);
viewHolder.actualSpeed = cell.findViewById(R.id.actualSpeed);
viewHolder.moreInfoButton = cell.findViewById(R.id.button);
viewHolder.frameLayoutUnfolded = cell.findViewById(R.id.frameLayoutUnfolded);
viewHolder.planetOrStarNameUnfolded = cell.findViewById(R.id.planetOrStarNameUnfolded);
cell.setTag(viewHolder);
} else {
// for existing cell set valid valid state(without animation)
if (unfoldedIndexes.contains(position)) {
cell.unfold(true);
} else {
cell.fold(true);
}
viewHolder = (ViewHolder) cell.getTag();
}
if (null == solarSystemItemFoldingCell)
return cell;
// bind data from selected element to view through view holder
viewHolder.planetOrStarNameFolded.setText(solarSystemItemFoldingCell.getPlantOrStarNameFolded());
viewHolder.actualMass.setText(solarSystemItemFoldingCell.getActualMass());
viewHolder.actualDistance.setText(solarSystemItemFoldingCell.getActualDistance());
viewHolder.actualDiameter.setText(solarSystemItemFoldingCell.getActualDiameter());
viewHolder.actualSpeed.setText(solarSystemItemFoldingCell.getActualSpeed());
viewHolder.planetOrStarNameUnfolded.setText(String.valueOf(solarSystemItemFoldingCell.getPlanetOrStarNameUnfolded()));
//setting Fonts
viewHolder.planetOrStarNameFolded.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.mass.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.distance.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.diameter.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.speed.setTypeface(App.getAppInstance().getArvoBold());
viewHolder.actualMass.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.actualDistance.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.actualDiameter.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.actualSpeed.setTypeface(App.getAppInstance().getArvoRegular());
viewHolder.moreInfoButton.setTypeface(App.getAppInstance().getArvoRegular());
// set custom btn handler for list item from that item
if (solarSystemItemFoldingCell.getRequestBtnClickListener() != null) {
viewHolder.moreInfoButton.setOnClickListener(solarSystemItemFoldingCell.getRequestBtnClickListener());
} else {
// (optionally) add "default" handler if no handler found in item
viewHolder.moreInfoButton.setOnClickListener(defaultRequestBtnClickListener);
}
viewHolder.relativeLayoutFolded.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Something gets clicked", Toast.LENGTH_SHORT).show();
viewHolder.foldingCell.fold(false);
registerFold(incomingPosition);
}
});
return cell;
}
// simple methods for register cell state changes
public void registerToggle(int position) {
if (unfoldedIndexes.contains(position)) {
registerFold(position);
incomingPosition = position;
}else
registerUnfold(position);
}
public void registerFold(int position) {
unfoldedIndexes.remove(position);
}
public void registerUnfold(int position) {
unfoldedIndexes.add(position);
}
public View.OnClickListener getDefaultRequestBtnClickListener() {
return defaultRequestBtnClickListener;
}
public void setDefaultRequestBtnClickListener(View.OnClickListener defaultRequestBtnClickListener) {
this.defaultRequestBtnClickListener = defaultRequestBtnClickListener;
}
// View lookup cache
private static class ViewHolder {
RelativeLayout relativeLayoutFolded ;
LinearLayout linearLayoutFolded ;
TextView planetOrStarNameFolded;
TextView mass;
TextView actualMass;
TextView distance;
TextView actualDistance;
TextView diameter;
TextView actualDiameter;
TextView speed;
TextView actualSpeed ;
Button moreInfoButton ;
FrameLayout frameLayoutUnfolded ;
TextView planetOrStarNameUnfolded;
FoldingCell foldingCell ;
}
}
SolarSystemClass
private void listViewIntegration (){
arrayList = addingDataIntoList();
solarSystemFoldingCellListAdapter = new SolarSystemFoldingCellListAdapter(SolarSystem.this , arrayList);
listView.setAdapter(solarSystemFoldingCellListAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int duration = 500; //miliseconds
int offset = 0; //fromListTop
listView.smoothScrollToPositionFromTop(position,offset,duration);
// toggle clicked cell state
((FoldingCell) view).toggle(false);
// register in adapter that state for selected cell is toggled
solarSystemFoldingCellListAdapter.registerToggle(position);
// listView.smoothScrollToPosition(position);
}
});
}
I have a gridView on my mainScreen fragment which contains imageViews initialized by my ImageAdapter.java class. I also have another fragment which also has a gridView which follows the same initialization process. What i want is to pass the selected imaveView's icon(which is stored in an Integer[] array) to the other fragment's gridView.
Here are my classes:
MainFragment.java [the part that handles the image passing]:
// When an item in the context menu gets selected, call a method
#Override
public boolean onContextItemSelected(MenuItem item) {
// Get some extra info about the contextMenu
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = info.position; // clicked view's position
if(item.getTitle().equals("Add Card to GLB")) {
addCardMessage(position, "added to GLB");
addSelectedCardToGlobalUserBox(position);
} else if (item.getTitle().equals("Add Card to JP")) {
addCardMessage(position , "added to JP");
} else
{
return false;
}
return false;
}
/**
* Creates a snackbar message, telling the user which card was added to which box
* #param id The position of the chosen card
* #param text Defines into which User Box the card was added
*/
private void addCardMessage(int id, String text) {
final Snackbar snackbar = Snackbar.make(gridView, id + " " + text ,Snackbar.LENGTH_LONG);
snackbar.setAction("Dismiss", new View.OnClickListener() {
#Override
public void onClick(View view) {
snackbar.dismiss();
}
});
snackbar.setActionTextColor(Color.MAGENTA);
snackbar.show();
}
private void addSelectedCardToGlobalUserBox(int position) {
ImageAdapter imageAdapter = new ImageAdapter(getContext());
UserBoxGlbImageAdapter userBoxGlbImageAdapter = new UserBoxGlbImageAdapter(getContext());
userBoxGlbImageAdapter.getGLBIconsList().add(imageAdapter.getmThumbIds(position));
int glbiconSize = userBoxGlbImageAdapter.getCount();
Toast.makeText(getActivity(), "Selected icon: " + imageAdapter.getmThumbIds(position), Toast.LENGTH_SHORT).show();
}
ImageAdapter.java [above fragment's adapter]:
public class ImageAdapter extends BaseAdapter {
Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
// If it's not recycled, initialize some attributes
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
public Integer getmThumbIds(int index) {
return mThumbIds[index];
}
// References to our images
private Integer[] mThumbIds = {
R.mipmap.turvegitossj_phy,
R.mipmap.goget_ur_int,
R.mipmap.turgogetassj4_teq,
R.mipmap.turgotenksssj_uragl,
R.mipmap.lr_phy_trunks_ssj
};
}
SecondFragment.java:
public class UserBoxGLBFragment extends Fragment {
GridView globalGridView;
public UserBoxGLBFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_box_glb, container, false);
globalGridView = view.findViewById(R.id.userBoxGlbGridView);
globalGridView.setAdapter(new UserBoxGlbImageAdapter(getContext()));
return view;
}
}
SecondFragmentAdapter[the one to receive the image]:
public class UserBoxGlbImageAdapter extends BaseAdapter {
Context mContext;
public UserBoxGlbImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return mGLBIcons.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
// References to the images via a List
private List<Integer> mGLBIcons = new ArrayList<>();
// Used to add card icons from the mainScreenFragment
public List<Integer> getGLBIconsList() {
return mGLBIcons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
// If it's not recycled, initialize some attributes
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mGLBIcons.get(position));
return imageView;
}
}
So far, when i long-press and the context menu opens, i click on add card to GLB but the image doesn't pass to the 2nd fragmnet's gridView. From what i understand, the Integer that i am using to add the imageResource to the 2nd grid does not work properly. What do i need to do? Do i need to use a different var type for my receiver list?
I have a dialog and I want to add a recyclerView or listView and I know that I have to use a List to control items in each row. Now when I want to change a value of a checkbox or a radioButton all the data in List are changing. I used Log and I got that all the booleans data changed at the same time. I moved all items to an activity but the problem still remains. It seems there is a link between the arrayList data.
Also I changed my codes and used SwitchCompat but all Boolean data in mDataSet are changing when I want to change just one of them.
public class AdapterSetOnOffTime extends RecyclerView.Adapter<AdapterSetOnOffTime.ViewHolder> {
private Context mContext;
private ArrayList<StructSetOnOffTime> mDataSet;
private View mView;
public AdapterSetOnOffTime(Context context, ArrayList<StructSetOnOffTime> dataSet) {
mContext = context;
mDataSet = dataSet;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int id = R.layout.layout_list_settime_items;
mView = LayoutInflater.from(mContext).inflate(id, parent, false);
return new ViewHolder(mView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mSwitch.setChecked(mDataSet.get(position).setOnOffValue);
holder.mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked){
mDataSet.get(position).setOnOffValue = true;
}else{
mDataSet.get(position).setOnOffValue = false;
}
}
});
}
#Override
public int getItemCount() {
return mDataSet.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextTitle;
public TextView mTextValue;
public ImageButton mBtn;
public SwitchCompat mSwitch;
public ViewHolder(View itemView) {
super(itemView);
mTextTitle = (TextView) itemView.findViewById(R.id.txtSetTime);
mTextValue = (TextView) itemView.findViewById(R.id.txtOnOffStatus);
mBtn = (ImageButton) itemView.findViewById(R.id.btnSetTime);
mSwitch = (SwitchCompat) itemView.findViewById(R.id.swPrefSwitch);
}
}
}
Update answer
After wasting a day I recognized that I made a little mistake to fill ArrayList and I'm going to share it.
Previous method of fill adapter:
StructSetOnOffTime item = new StructSetOnOffTime();
ArrayList<StructSetOnOffTime> arrayList = new ArrayList<>();
for(int i = 0; i < 9; i++){
item.setTimeValue = null;
item.setOnOffValue = false;
arrayList.add(item);
}
As #Anatoli said, I had a problem in this section and I solved it by changing the upper method to this one:
ArrayList<StructSetOnOffTime> arrayList = new ArrayList<>();
for(int i = 0; i < 9; i++){
StructSetOnOffTime item = new StructSetOnOffTime();
item.setTimeValue = null;
item.setOnOffValue = false;
arrayList.add(item);
}
You set to radOn and radOff same OnCheckedChangeListener and checks in listener if it was set to true. Why you don't make 2 listeners?
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mDataSet.get(position).onOffStatus = true;
// update adapter
notifyDataSetChanged();
}
}
};
holder.radOn.setOnCheckedChangeListener(listener);
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mDataSet.get(position).onOffStatus = false;
// update adapter
notifyDataSetChanged();
}
}
};
holder.radOff.setOnCheckedChangeListener(listener);
looks much simpler
calling of
holder.radOn.setChecked(holder.radOn == buttonView);
holder.radOff.setChecked(holder.radOff == buttonView);
triggers the listeners. To update values in list, just call adapter.notifyDataSetChanged();
UPDATE
For each new item in list you must initialize new Holder
RecyclerView
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
// Inflate the custom layout
View itemView = LayoutInflater.from(parent.getContext())
.inflate(layoutId, parent, false);
return new Holder(itemView, viewType);
}
ArayList
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
Holder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
viewHolder = new Holder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (Holder) convertView.getTag();
}
Item item = getItem(position);
fill(item, position);
return convertView;
}
When ever you set the check state of your view(from your code also if view didn't get destroyed) your check listener will get called so you need to manually maintain the state. It will work for all radiobutton, checkbox etc.
holder.mSwitch.setOnCheckedChangeListener(null);
holder.mSwitch.setChecked(mDataSet.get(position).setOnOffValue);
holder.mSwitch.setOnClickListener(new OnClickListener(){
//holder.mSwitch.setCheck(!mDataSet.get(position).setOnOffValue);
mDataSet.get(position).setOnOffValue = !mDataSet.get(position).setOnOffValue;
});
I'm new to android studio and I'm working on a project. I have a ListView and it consists of CheckBox and TextView. I've added two buttons add and delete. If I check the CheckBox and press the delete button, that item is deleted. Thus, I designed a custom adapter and it has a getView() method.
This getView() method includes a listener for CheckBox. When I check the CheckBox, is the getView() method called or only listener is executed?
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
final int pos = position;
rowView = myInflater.inflate(R.layout.row_layout, null);
TextView textView = (TextView)rowView.findViewById(R.id.content);
final CheckBox checkBox = (CheckBox)rowView.findViewById(R.id.check);
textView.setText( list.get(pos).getContent() );
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( checkBox.isChecked() ){
list.get(pos).setChecking(1);
}
else {
list.get(pos).setChecking(0);
}
}
});
return rowView;
}
When I check the checkbox, is the getView() method called or only
listener is executed ?
Only the code within your listener will be executed. In this case:
if( checkBox.isChecked() )
{
list.get(pos).setChecking(1);
}
else
{
list.get(pos).setChecking(0);
}
Adapter's getView() is called everytime the view for the list item is either created or reused. This method is executed before the user gets to see the item (for this reason it is recommended to keep this method short and free from heavy computations).
When the checkbox is checked, getView() will not be called rather the listener of the checkbox will be called. In this particular case what you are trying to achieve you will have to set a OnCheckedChangeListener and OnClickListener to checkbox and button respectively.
Your CustomAdapter.java will look something like this:
public class CustomAdapter extends BaseAdapter {
Context context;
List<String> list;
public static List<Integer> selectedPositions;
public CustomAdapter(Context context,List<String> list){
this.context=context;
this.list=list;
this.selectedPositions=new ArrayList<>(0);
}
#Override
public int getCount() {
return list==null?0:list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
View vi = convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate rowitem.xml file for each row ( Defined below ) *******/
vi = LayoutInflater.from(context).inflate(R.layout.row_item, null);
/****** View Holder Object to contain rowitem.xml file elements ******/
holder = new ViewHolder(vi);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
//Set listeners for checkbox and button
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.isChecked()){
selectedPositions.add(position);
}else{
int count=0;
for(int item:selectedPositions){
if(item==position){
selectedPositions.remove(count);
}
count++;
}
}
}
});
return vi;
}
private class ViewHolder{
CheckBox checkBox;
TextView textView;
ViewHolder(View itemView){
checkBox=(CheckBox)itemView.findViewById(R.id.checkbox);
textView=(TextView)itemView.findViewById(R.id.textView);
}
}
}
The Delete Button in the activity will be handeled like this :
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(CustomAdapter.selectedPositions != null &&
!CustomAdapter.selectedPositions.isEmpty()){
for(int count = 0;
count < CustomAdapter.selectedPositions.size(); count++){
list.remove(CustomAdapter.selectedPositions.get(count));
adapter.notifyDataSetChanged();
}
}
}
});
i m developing an application in which gridview contain list of button...
when i place images instead of button in gridview then onItemClickEvent get fired..but if i place button in gridView then click event not getting callled...i dont know what is the problem...even i m not getting exception..
here is my code...
public class MainMenu extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.mainMenu);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Toast.makeText(MainMenu.this, "hello" + position, Toast.LENGTH_SHORT).show();
}
});
}
//inner class for adapter
class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c)
{
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
//ImageView imageView;
Button btn;
if (convertView == null) { // if it's not recycled, initialize some attributes
btn=new Button(mContext);
// imageView = new ImageView(mContext);
btn.setLayoutParams(new GridView.LayoutParams(120,120));
// imageView.setLayoutParams(new GridView.LayoutParams(140,140));
//imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
btn.setPadding(10,15, 10,15);
btn.setImeActionLabel("hello",0);// actionId)
// imageView.setPadding(8,8, 8, 8);
} else
{
btn=(Button)convertView;
//imageView=(ImageView)convertView;
}
btn.setBackgroundResource(mThumbIds[position]);
//imageView.setImageResource(mThumbIds[position]);
//return imageView;
return btn;
}
// references to our images
private Integer[] mThumbIds =
{
R.drawable.pantrylocator_icon,
R.drawable.volunteeropportunity_icon,
R.drawable.volunteerlocator_icon,
R.drawable.volunteermanagement_icon,
R.drawable.donationform_icon,
R.drawable.donationviamsg_icon,
R.drawable.donationvideo_icon,
R.drawable.virtualfooddrive_icon,
R.drawable.newevent_icon,
R.drawable.pressrelease_icon,
R.drawable.volunteerphotos_icon,
R.drawable.aboutus_icon,
};
}
}
The button has its own OnClickListener:
public View getView(int position, View convertView, ViewGroup parent) {
//ImageView imageView;
Button btn;
if (convertView == null) { // if it's not recycled, initialize some attributes
btn=new Button(mContext);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
// imageView = new ImageView(mContext);
btn.setLayoutParams(new GridView.LayoutParams(120,120));
// imageView.setLayoutParams(new GridView.LayoutParams(140,140));
//imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
btn.setPadding(10,15, 10,15);
btn.setImeActionLabel("hello",0);// actionId)
// imageView.setPadding(8,8, 8, 8);
} else
{
btn=(Button)convertView;
//imageView=(ImageView)convertView;
}
btn.setBackgroundResource(mThumbIds[position]);
//imageView.setImageResource(mThumbIds[position]);
//return imageView;
return btn;
}
In your ImageAdapter-> getView method add the following line before returning newly created "convertView"
convertView.setClickable(false);
convertView.setFocusable(false);
If any of the views in gridview are clickable then they will block the grid's ItemClick listener from responding.
There is no onclick event written for the Buttons you are adding. Write code for the buttons to handle the click event! let us know then.
i have fece this problem also but finally got the solution i have follow the above suggession
and define button click event in base adapter class like as
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v;
if(convertView==null){
LayoutInflater li = LayoutInflater.from(mContext);
v = li.inflate(R.layout.icon, null);
tv = (Button)v.findViewById(R.id.icon_text);
iv = (ImageView)v.findViewById(R.id.icon_image);
iv.setImageResource(mThumbIds[position]);
tv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(mContext, "vim", Toast.LENGTH_LONG).show();
}
});
}
else
{
v = (View)convertView;
}
return v;
}
gridview = (GridView) findViewById(R.id.gameGrid);
gridview.setAdapter(ia);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Ur Code here
}
Add click events for the button added in gridView
Here's the cleanest way to do it: call performItemClick() on the GridView from within each button's click listener. That way you can still use the GridView's onItemClickListener like normal.
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
...
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((GridView) parent).performItemClick(v, position, 0);
}
});
}
http://www.migapro.com/click-events-listview-gridview/
I have solved my problem as i define button click event in base adpter class and my problem is solved......