I need to update my gridView when I click on an item. I've try a lot a things but nothing works.
I have the following code for my activity:
public class GameActivity extends AppCompatActivity implements IGameView{
public GridGame _gridGame = new GridGame();
public GamePresenter _presenter = new GamePresenter(this, _gridGame);
public ImageAdapter _imageAdapter = new ImageAdapter(this, _gridGame);
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_help) {
Intent intent = new Intent(this, HelpActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
final Context context = this;
final GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(_imageAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
_presenter.addPawn(position);
_imageAdapter.update(position, _presenter.actualPlayer);
Toast.makeText(context, "" + position,Toast.LENGTH_SHORT).show();
}
});
}
And imageAdapter's code :
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private GridGame _gridGame;
public ImageAdapter(Context c, GridGame grid) {
mContext = c;
_gridGame = grid;
}
public int getCount() {
return grid.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;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new ViewGroup.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
setGrid();
imageView.setImageResource(grid[position]);
return imageView;
}
private Integer[] grid = new Integer[42];
public void setGrid() {
for(int i = 0; i < 42; i++){
grid[i] = R.drawable.square;
}
}
public void update(int id, int player){
grid[id] = R.drawable.ic_notifications_black_24dp;
}
When I click on a square (item on the gridview) i want that the view update a show an other image instead of the square. The update is done when I call update method on the ImageAdapter but the view don't update.
First you need to fix the methods to return the desired data for adapter to identify the item objects as
// return the new data from sourcein case of update
public Object getItem(int position) {
return grid[position];
}
// don't send 0 always
public long getItemId(int position) {
return position;
}
// invoke notifyDataSetChanged(); when there is a change in data source
public void update(int id, int player){
grid[id] = R.drawable.ic_notifications_black_24dp;
notifyDataSetChanged();
}
You need to notify the adapter that a data element has changed. Try this update() method:
public void update(int id, int player){
grid[id] = R.drawable.ic_notifications_black_24dp;
notifyDataSetChanged();
}
Ok, I've found the problem, I was setting the grid in the getView(int position, View convertView, ViewGroup parent); but it should be set in the constructor.
The problem was that it reset the value in the grid each time I click on an item, so the value didn't changed.
Related
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'm new to android studios and am currently about to finish up on my first project. However, I'm stuck at the part where I have to pass the value selected from the listview to the next activity. I have tried researching on the codes but none seem to be able to work. Any help would be greatly appreciated.
DisplayProduct.java
public class DisplayProduct extends AppCompatActivity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
DatabaseHelper databaseHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_product);
listView = (ListView)findViewById(R.id.listView);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.display_product_row);
listView.setAdapter(listDataAdapter);
databaseHelper = new DatabaseHelper(getApplicationContext());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//Object data = parent.getItemAtPosition(position);
//String value = data.toString();
}
});
sqLiteDatabase = databaseHelper.getReadableDatabase();
cursor = databaseHelper.getInformations(sqLiteDatabase);
if(cursor.moveToFirst())
{
do {
String contact,location,issue;
contact = cursor.getString(0);
location = cursor.getString(1);
issue = cursor.getString(2);
Information information = new Information(contact,location,issue);
listDataAdapter.add(information);
} while (cursor.moveToNext());
}
}
}
ListDataAdapter.java
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView Contact,Location,Issue;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.display_product_row, parent, false);
layoutHandler = new LayoutHandler();
layoutHandler.Contact = (TextView) row.findViewById(R.id.textView8);
layoutHandler.Location = (TextView) row.findViewById(R.id.textView18);
layoutHandler.Issue = (TextView) row.findViewById(R.id.textView90);
row.setTag(layoutHandler);
} else {
layoutHandler = (LayoutHandler) row.getTag();
}
Information information = (Information) this.getItem(position);
layoutHandler.Contact.setText(information.getContact());
layoutHandler.Location.setText(information.getLocation());
layoutHandler.Issue.setText(information.getIssue());
return row;
}
}
LocationDetail.java
public class LocationDetail extends AppCompatActivity {
private TextView Textv;
DatabaseHelper databaseHelper;
SQLiteDatabase sqlitedatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_detail);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_location_detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
From DisplayProduct.java :
Intent intent = new Intent(this, LocationDetail.class);
Object data = parent.getItemAtPosition(position);
String message = data.toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
From LocationDetail.java:
Intent intent = getIntent();
String value = intent.getStringExtra(EXTRA_MESSAGE);
I am trying to delete multiple checked rows from listview when click on the delete icon on action bar. However i get these nullpointerexception, i think the problem would be on adapter and dbHelper as i only declare them, but i do not know how i can solve this.
public class MainActivity extends ActionBarActivity {
public static TaskerDbHelper dbHelper;
public static ListView listviewTasks;
public static List<Task> arrayTasks;
public static TaskAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new TaskerDbHelper(this);
arrayTasks = dbHelper.getAllTasks();
listviewTasks = (ListView) findViewById(R.id.Tasks_onDate);
adapter = new TaskAdapter(this,arrayTasks);
listviewTasks.setAdapter(adapter);
listviewTasks.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Intent detailIntent = new Intent(MainActivity.this, DetailTaskActivity.class);
detailIntent.putExtra("rowID", (int)id);
startActivity(detailIntent);
}
});
#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 super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch(item.getItemId()){
case R.id.action_search:
return true;
case R.id.action_add:
Intent Addintent = new Intent(MainActivity.this, AddTaskActivity.class);
startActivity(Addintent);
return true;
case R.id.action_delete:
SparseBooleanArray checkedItems = listviewTasks.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++){
if(checkedItems.valueAt(i)){
dbHelper.deleteTask((int)adapter.getItemId(i));
}
}
listviewTasks.invalidateViews();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
and the log is
http://i.stack.imgur.com/OqLuN.png
My guess is to work with a extended ArrayAdapter. This worked like a charm for me for multiple click->delete listview.
I declared it all like this:
arrayAdapter = new ListAdapter(this,R.layout.list_item, **YOUR LIST**);
listview.setAdapter(arrayAdapter);
listview.setCacheColorHint(Color.TRANSPARENT);
selectedItems = new ArrayList<Integer>();
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
ArrayList<Integer> selectedIds = arrayAdapter.selectedid;
Integer pos = new Integer(position);
if(selectedIds.contains(pos)) {
selectedIds.remove(pos);
}
else {
selectedIds.add(pos);
}
arrayAdapter.notifyDataSetChanged();
}
});
The class I extended.
public class ListAdapter extends ArrayAdapter<ChartItem> {
Context context;
protected ArrayList<**YOUR LIST ITEM**> list;
LayoutInflater inflater;
ArrayList<Integer> selectedid;
public ListAdapter(Context context, int layoutResourceId ,ArrayList<ChartItem> ticket) {
super(context,layoutResourceId,ticket);
selectedid = new ArrayList<Integer>();
this.list = **ARRAY YOU WANT TO LIST**;
this.inflater = LayoutInflater.from(context);
this.context = context;
}
public int getCount() {
return list.size();
}
public ChartItem getItem(int position) {
return list.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.list_item, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.rowTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ChartItem item = list.get(position);
TextView tv = (TextView) convertView.findViewById(R.id.rowTextView);
tv.setText(item.getName());
TextView tv2 = (TextView) convertView.findViewById(R.id.rowTextView2);
tv2.setText(String.valueOf(item.getPrice()));
if(selectedid.contains(position)){
tv.setBackgroundColor(Color.DKGRAY);
tv.setTextColor(Color.WHITE);
}
else{
tv.setBackgroundColor(Color.TRANSPARENT);
tv.setTextColor(Color.BLACK);
}
return convertView;
}
private class ViewHolder {
TextView name;
}
}
I really had allot of trouble with this aswell and I think this is the best way to do it so far.
If you need any more help or when you have questions about this code snippet let me know!
It is actually the checkedItems is null.
I actually wanna reach something like this. So when user checked the rows, they may delete or mark it as completed
http://i.stack.imgur.com/k4jKT.png
I solve it from another approaches like below.
case R.id.action_delete:
for(int i = 0; i < arrayTasks.size();i++){
if((CheckBox)listviewTasks.getChildAt(i).findViewById(R.id.selected) != null){
CheckBox cBox=(CheckBox)listviewTasks.getChildAt(i).findViewById(R.id.selected);
if(cBox.isChecked()){
dbHelper.deleteTask((int)adapter.getItemId(i));
}
}
}
adapter.notifyDataSetChanged();
return true;
I juz change the action_delete for the onoptionitemselected function.
[1]:
HomeFragment
imports;
public class HomeFragment extends Fragment {
// Declare Variables
ListView list;
TextView text;
ListViewAdapter adapter;
EditText editsearch;
String[] title;
String[] date;
String[] status;
ArrayList<ListCourse> arraylist = new ArrayList<ListCourse>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
date = new String[] { "11/01/2011", "10/05/2006", "12/07/2002", "05/04/2011", "01/08/2012",
"09/12/2017", "22/06/2024", "31/01/2000", "10/10/2156", "10/02/2006" };
title = new String[] { "Programação", "Matemática", "Logística",
"Mobile", "Sistemas Operativos", "iOS", "Android", "Windows",
"Hardware", "Formação" };
status = new String[] { " ongoing ", " ongoing ",
" ongoing ", " standby ", " ongoing ", " ongoing ",
" ongoing ", " ongoing ", " finished ", " ongoing " };
// Locate the ListView in listview_main.xml
list = (ListView) rootView.findViewById(R.id.listview);
for (int i = 0; i < title.length; i++)
{
ListCourse wp = new ListCourse(date[i], title[i],
status[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(getActivity(), arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
return rootView;
}
}
I just need 3 items on the context menu: Like, Comment and Favorite. I tried implementing various tutorials to no avail, my project consist of a MainActivity that has a slidermenu to open some fragments like this one where the list is and where I want to put the context menu.
Here´s my adapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<ListCourse> coursepopulatelist = null;
private ArrayList<ListCourse> arraylist;
public ListViewAdapter(Context context, List<ListCourse> coursepopulatelist) {
mContext = context;
this.coursepopulatelist = coursepopulatelist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ListCourse>();
this.arraylist.addAll(coursepopulatelist);
}
public class ViewHolder {
TextView title;
TextView date;
TextView status;
}
#Override
public int getCount() {
return coursepopulatelist.size();
}
#Override
public ListCourse getItem(int position) {
return coursepopulatelist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.title = (TextView) view.findViewById(R.id.title);
holder.date = (TextView) view.findViewById(R.id.date);
holder.status = (TextView) view.findViewById(R.id.status);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.title.setText(coursepopulatelist.get(position).getTitle());
holder.date.setText(coursepopulatelist.get(position).getDate());
holder.status.setText(coursepopulatelist.get(position).getStatus());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("title",(coursepopulatelist.get(position).getTitle()));
// Pass all data country
intent.putExtra("date",(coursepopulatelist.get(position).getDate()));
// Pass all data population
intent.putExtra("status",(coursepopulatelist.get(position).getStatus()));
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
coursepopulatelist.clear();
if (charText.length() == 0) {
coursepopulatelist.addAll(arraylist);
}
else
{
for (ListCourse wp : arraylist)
{
if (wp.getDate().toLowerCase(Locale.getDefault()).contains(charText))
{
coursepopulatelist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Are the changes supposed to go in the adapter or the fragment? I tried several times with OnCreateContextMenu and ContextMenuSelectedItem cant get it to work on the fragment, also tried OnLongItemClick. Any help would be appreciated.
I managed to get one context menu working, right here:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
adapter = new ListViewAdapter(getActivity(), arraylist);
Object item = adapter.getItem(info.position);
menu.setHeaderTitle("Opções");
menu.add(0, v.getId(), 0, "Like");
menu.add(1, v.getId(), 0, "Comment");
menu.add(2, v.getId(), 0, "Favorite");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Like") {
addLike(item.getItemId());
} else if (item.getTitle() == "Comment") {
} else if (item.getTitle() == "Favorite") {
// code
} else {
return false;
}
return true;
}
public void addLike(int id){
}
Right after the return rootView in the HomeFragment. Also had to add android:longClickable="true" on the listview.xml or it would never work (I put it into the listviewitem.xml too just in case).
first set your listvieW as follow myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myListView.setAdapter(adapter);
then register for MultiChoiceModeListener and override his methods in your liking :)
myListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// here you will inflate your CAB
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
Here is the link
My application intend to select image switcher content based on one of two selected radio button. on radio button click, the application does not choose desired option and finally the application crashed.
The big problem is i want to free the array holding images for the swicher based on the radio button checked.
Also, there are two arrays with image reference to it. i want to delete all the array inside the gallery and add one of the reference. Here is my code.
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
//check which id is selected
radioCheckedId= checkedId;
//radio button checked
switch(radioCheckedId){
case R.id.radBtnAccident:
//delete all array
if (pics.length>0){
for (int arr=0;arr<pics.length;arr++){
pics[arr]=null;
}
}
//populates array
pics = new Integer[]{ R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d,
R.drawable.e,R.drawable.exit, R.drawable.plan, R.drawable.icon, R.drawable.plan };
chooseImgArray(pics);
break;
case R.id.radBtnOthers:
//populates other array
pics = new Integer[]{R.drawable.exit, R.drawable.plan,
R.drawable.icon, R.drawable.plan,R.drawable.c };
chooseImgArray(pics);
break;
default:
break;
}
}
public void chooseImgArray(final Integer[] array){
iSwitcher = (ImageSwitcher) findViewById(R.id.ImgSwith);
iSwitcher.setFactory(this);
iSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
iSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));
gallery = (Gallery) findViewById(R.id.galImage);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int count,long arg3) {
iSwitcher.setImageResource(array[count]);
}
});
}
I put Example code for ImageSwitcher with Gallery Check it.
it is usefull to u.
public class TestActivity extends Activity implements ViewFactory,
OnItemSelectedListener {
private Gallery gallery;
private ImageSwitcher iSwitcher;
private RadioGroup rdgSelection;
private Boolean flag = true;
private Integer[] Array1 = { R.drawable.arrow, R.drawable.arrow1,
R.drawable.arrow2, R.drawable.arrow3 };
private Integer[] Array2 = { R.drawable.camera, R.drawable.camera1,
R.drawable.camera2, R.drawable.camera3 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gallery = (Gallery) findViewById(R.id.gallery);
iSwitcher = (ImageSwitcher) findViewById(R.id.imgSwitcher);
rdgSelection = (RadioGroup) findViewById(R.id.rdgSelection);
iSwitcher.setFactory(this);
rdgSelection.check(rdgSelection.getChildAt(
rdgSelection.getChildCount() - 1).getId());
if (rdgSelection.getCheckedRadioButtonId() == R.id.rdb1) {
flag = true;
gallery.setAdapter(new ImageAdapter(TestActivity.this));
} else {
flag = false;
gallery.setAdapter(new ImageAdapter(TestActivity.this));
}
rdgSelection.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
gallery.setAdapter(new ImageAdapter(TestActivity.this));
if (rdgSelection.getCheckedRadioButtonId() == R.id.rdb1)
flag = true;
else
flag = false;
}
});
gallery.setOnItemSelectedListener(this);
}
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
if (flag)
return Array1.length;
else
return Array2.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
if (flag)
i.setImageResource(Array1[position]);
else
i.setImageResource(Array2[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
return i;
}
private Context mContext;
}
#Override
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return i;
}
#Override
public void onItemSelected(AdapterView<?> arg0, View v, int position,
long id) {
if (flag)
iSwitcher.setImageResource(Array1[position]);
else
iSwitcher.setImageResource(Array2[position]);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}