Delete Animation not Working in Recyclerview When using ActionModeBar - android

I am selecting multiple items in my recylcerview and when i delete these multiple items using Action mode bar then default delete animation is not showing but when i am deleting item single then animation plays?
This is my MainActivity.
public class MainActivity extends AppCompatActivity implements android.view.ActionMode.Callback {
public static boolean list_layout = true;
SwipeRefreshLayout swipeRefreshLayout;
RecyclerView recyclerView;
ActionMode actionMode;
MyAdapter adapter;
private List<Person> persons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addOnItemTouchListener(new RecyclerViewTouchListener(this, recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Toast.makeText(MainActivity.this, "onClick " + position, Toast.LENGTH_SHORT).show();
if (actionMode != null) {
myToggleSelection(position);
}
if (adapter.getSelectedItemCount() == 0 && actionMode != null) {
actionMode.finish();
}
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(MainActivity.this, "onLongClick " + position, Toast.LENGTH_SHORT).show();
if (actionMode != null) {
return;
}
actionMode = startActionMode(MainActivity.this);
myToggleSelection(position);
}
}));
initializeData();
adapter = new MyAdapter(this, persons);
recyclerView.setAdapter(adapter);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshSwipe);
swipeRefreshLayout.setColorSchemeColors(Color.BLUE, Color.GREEN, Color.RED, Color.DKGRAY);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
}
});
}
private void myToggleSelection(int idx) {
adapter.toggleSelection(idx);
String title = getString(R.string.selected_count, adapter.getSelectedItemCount());
actionMode.setTitle(adapter.getSelectedItemCount() + " Selected");
}
private void initializeData() {
persons = new ArrayList<>();
for (int i = 0; i < 5; i++) {
persons.add(new Person("Emma Wilson", "23 years old", R.mipmap.ic_launcher));
persons.add(new Person("Lavery Maiss", "25 years old", R.mipmap.ic_launcher));
persons.add(new Person("Lillie Watts", "35 years old", R.mipmap.ic_launcher));
}
}
#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_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_settings) {
if (list_layout) {
list_layout = false;
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
MyAdapter adapter = new MyAdapter(this, persons);
recyclerView.setAdapter(adapter);
item.setIcon(R.drawable.abc_ic_menu_copy_mtrl_am_alpha);
} else {
list_layout = true;
recyclerView.setLayoutManager(new LinearLayoutManager(this));
MyAdapter adapter = new MyAdapter(this, persons);
recyclerView.setAdapter(adapter);
item.setIcon(R.drawable.abc_ic_menu_selectall_mtrl_alpha);
}
return true;
}
return super.onOptionsItemSelected(item);
}
// Action Mode Methods
#Override
public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_cab_recyclerviewdemoactivity, menu);
return true;
}
#Override
public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
List<Integer> selectedItemPositions = adapter.getSelectedItems();
for (int i = selectedItemPositions.size() - 1; i >= 0; i--) {
adapter.remove(selectedItemPositions.get(i));
}
actionMode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(android.view.ActionMode mode) {
this.actionMode = null;
adapter.clearSelections();
}
// Interface
interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
This my Adapter class.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
List<Person> persons;
LayoutInflater inflater;
Context context;
private int previousPosition = 0;
private boolean deleting = false;
private boolean isGridLayout = false;
private boolean isOddCard = true;
private SparseBooleanArray selectedItems = new SparseBooleanArray();
private SparseBooleanArray mSelectedPositions = new SparseBooleanArray();
private boolean mIsSelectable = false;
private boolean selecting = false;
public MyAdapter(Context context, List<Person> persons) {
this.persons = persons;
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int resource = R.layout.cardview_list_item;
if (!MainActivity.list_layout) {
resource = R.layout.cardview_grid_item;
isGridLayout = true;
} else {
isGridLayout = false;
}
View view = inflater.inflate(resource, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Person person = persons.get(position);
holder.personName.setText(person.name);
holder.personAge.setText(person.age);
holder.personPhoto.setImageResource(person.photoId);
holder.itemView.setActivated(selectedItems.get(position, false));
holder.overflowMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopMenu((ImageButton) v, holder);
}
});
}
private void showPopMenu(ImageButton button, final ViewHolder holder) {
PopupMenu popup = new PopupMenu(context, button);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.menu_card, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(context, "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
deleting = true;
int position = holder.getPosition();
remove(position);
return true;
}
});
popup.show();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return persons.size();
}
public void toggleSelection(int pos) {
if (selectedItems.get(pos, false)) {
selectedItems.delete(pos);
} else {
selectedItems.put(pos, true);
}
selecting = true;
notifyItemChanged(pos);
}
public void clearSelections() {
selectedItems.clear();
notifyDataSetChanged();
selecting = false;
}
public int getSelectedItemCount() {
return selectedItems.size();
}
public List<Integer> getSelectedItems() {
List<Integer> items =
new ArrayList<Integer>(selectedItems.size());
for (int i = 0; i < selectedItems.size(); i++) {
items.add(selectedItems.keyAt(i));
}
return items;
}
public void remove(int position) {
persons.remove(position);
deleting = true;
notifyItemRemoved(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
CardView cv;
ImageButton overflowMenu;
TextView personName;
TextView personAge;
ImageView personPhoto;
View itemView;
public ViewHolder(View itemView) {
super(itemView);
this.itemView = itemView;
cv = (CardView) itemView.findViewById(R.id.cardView);
overflowMenu = (ImageButton) itemView.findViewById(R.id.imageButton);
personName = (TextView) itemView.findViewById(R.id.person_name);
personAge = (TextView) itemView.findViewById(R.id.person_age);
personPhoto = (ImageView) itemView.findViewById(R.id.person_photo);
}
}
}

actionMode.finish() will stop the remove animation of your recycler view, because adapter.clearSelections() called in onDestroyActionMode()
use notifyItemRangeChanged(0, selectedItems.size()) instead of notifyDataSetChanged() in adapter.clearSelections() method can make the animation work

Related

When I opened the searched item, it is opening the first item of ListView not the searched one. Even if search and find the items successfuly

When I opened the searched item, it is opening the first item of ListView not the searched one. Even if search and find the items successfuly.
I configure the adapter with "implements Filterable" and enable Listview with ".setTextFilterEnabled(true)", but doesn´t work.
I saw that I must implement "public Filter getFilter()" but I have no idea how can I do that.
When I type some words in EditText, like "cel" or "12" the filter goes in action, but the result is always the same: The first two items in Listview, no matter what is into the Listview (the content of listview is random).
Below a snippet of my Activity:
public class MusicActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
private boolean checkPermission = false;
ProgressDialog progressDialog;
ListView listView;
List<String> songsNameList;
List<String> songsUrlList;
List<String> songsArtistList;
List<String> songsDurationList;
ListAdapter adapter;
JcPlayerView jcPlayerView;
List<JcAudio> jcAudios;
List<String> thumbnail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
progressDialog = new ProgressDialog(this);
progressDialog.show();
progressDialog.setMessage("Please Wait...");
listView = findViewById(R.id.songsList);
songsNameList = new ArrayList<>();
songsUrlList = new ArrayList<>();
songsArtistList = new ArrayList<>();
songsDurationList = new ArrayList<>();
jcAudios = new ArrayList<>();
thumbnail = new ArrayList<>();
jcPlayerView = findViewById(R.id.jcplayer);
retrieveSongs();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
jcPlayerView.playAudio(jcAudios.get(i));
jcPlayerView.setVisibility(View.VISIBLE);
jcPlayerView.createNotification();
adapter.notifyDataSetChanged();
}
});
}
// RETRIEVING THE SONGS FROM THE SERVER
public void retrieveSongs() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Songs");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
Song song = ds.getValue(Song.class);
songsNameList.add(song.getSongName());
songsUrlList.add(song.getSongUrl());
songsArtistList.add(song.getSongArtist());
songsDurationList.add(song.getSongDuration());
thumbnail.add(song.getImageUrl());
jcAudios.add(JcAudio.createFromURL(song.getSongName(), song.getSongUrl()));
}
adapter = new ListAdapter(getApplicationContext(), songsNameList, thumbnail, songsArtistList, songsDurationList);
jcPlayerView.initPlaylist(jcAudios, null);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(MusicActivity.this, "FAILED!", Toast.LENGTH_SHORT).show();
}
});
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.app_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.searchmenu:
startActivity(new Intent(MusicActivity.this,Search.class));
break;
case R.id.requestmenu:
startActivity(new Intent(MusicActivity.this,UploadSongActivity.class));
break;
case R.id.sharemenu:
break;
}
return true;
}*/
// Filter Class
// METHOD TO HANDEL RUNTIME PERMISSIONS
private boolean validatePermissions(){
Dexter.withContext(getApplicationContext())
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
checkPermission = true;
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
checkPermission = false;
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
return checkPermission;
}
#Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if(TextUtils.isEmpty(newText)){
adapter.filter("");
listView.clearTextFilter();
}else{
String texto = newText;
adapter.filter(newText);
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.searchmenu, menu);
MenuItem searchItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search Catholic songs");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.search) {
return true;
}
else if(id == R.id.Rate){
/*if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
//log.d("TAG", "The intersitial wasn't loaded yet.");
}*/
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + getString(R.string.packegname)));
startActivity(intent);
}
else if (id ==R.id.sharemenu){
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,
"Hey ! check out this music service that gives you access to Hundreds of catholic songs. through Catholic app at: https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
else if(id == R.id.uploadItem){
if (validatePermissions()){
Intent intent = new Intent(this,UploadSongActivity.class);
startActivity(intent);
}
}
return super.onOptionsItemSelected(item);
}
and below my CustomAdapter:
public class ListAdapter extends BaseAdapter {
List<String> songNames;
List<String> thumbnails;
List<String> songArtist;
List<String> songDuration;
Context context;
private List<String> copyList;
private int searchedItem = -1;
private ArrayList<Song> arraylist;
public ListAdapter(Context context, List<String> songNames, List<String> thumbnails, List<String> songArtist, List<String> songDuration) {
this.context = context;
this.songNames = songNames;
this.thumbnails = thumbnails;
this.songArtist = songArtist;
this.songDuration = songDuration;
copyList = new ArrayList<String>();
copyList.addAll(songNames);
}
#Override
public int getCount() {
return songNames.size();
}
#Override
public Object getItem(int i) {
return songNames.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#SuppressLint({"InflateParams", "ViewHolder"})
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
final ViewHolder viewHolder;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.songs_list_layout, null);
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
Transformation transformation = new RoundedTransformationBuilder()
.cornerRadiusDp(15)
.build();
Picasso.get().load(thumbnails.get(i)).transform(transformation).into(viewHolder.thumbnail);
viewHolder.songName.setText(songNames.get(i));
viewHolder.artistName.setText(songArtist.get(i));
viewHolder.songDuration.setText(songDuration.get(i));
return view;
}
public void filter(String queryText)
{
songNames.clear();
if(queryText.isEmpty())
{
songNames.addAll(copyList);
}
else
{
for(String name: copyList)
{
if(name.toLowerCase().contains(queryText.toLowerCase()))
{
songNames.add(name);
}
}
}
notifyDataSetChanged();
}
private static class ViewHolder{
TextView songName;
TextView artistName;
TextView songDuration;
ImageView thumbnail;
CardView cardView;
ImageView currentlyPlaying;
ViewHolder(View view){
songName = view.findViewById(R.id.songName);
thumbnail = view.findViewById(R.id.songThumbnail);
artistName = view.findViewById(R.id.artistName);
songDuration = view.findViewById(R.id.songDuration);
cardView = view.findViewById(R.id.cardView);
currentlyPlaying = view.findViewById(R.id.currentlyPlaying);
}
}
What is missing?
I improved your adapter, didn't test it but it should work... I think it's easier to forward the Song list than the lists for each field separately... You have the original list for filtering and filteredList for adapter views...
EDITED: You have to implement Filterable, sorry i didnt see this...
public class ListAdapter extends BaseAdapter implements Filterable {
private final Context context;
private final List<Song> songlist;
private final List<Song> filteredList;
public ListAdapter(Context context, List<Song> songlist) {
this.context = context;
this.songlist = songlist;
filteredList = new ArrayList<>();
filteredList.addAll(songlist);
}
#Override
public int getCount() {
return filteredList.size();
}
#Override
public Object getItem(int i) {
return filteredList.get(i); // return Song item
}
#Override
public long getItemId(int i) {
return i; //TODO change this to return song id
}
#SuppressLint({"InflateParams", "ViewHolder"})
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
final ViewHolder viewHolder;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.songs_list_layout, null);
viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
Transformation transformation = new RoundedTransformationBuilder()
.cornerRadiusDp(15)
.build();
Song song = filteredList.get(i);
Picasso.get().load(song.getImageUrl()).transform(transformation).into(viewHolder.thumbnail);
viewHolder.songName.setText(song.getSongName());
viewHolder.artistName.setText(song.getSongArtist());
viewHolder.songDuration.setText(song.getSongDuration());
return view;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering (CharSequence constraint) {
FilterResults results = new FilterResults();
if (songlist != null && constraint != null) {
filteredList.clear();
List<Song> newValues = new ArrayList<>();
for (Song song: songlist) {
if(constraint.length() == 0) {
newValues.add(song); //TODO change this if you want empty list
}else{
if(song.getSongName.toLowerCase().contains(constraint.toString().toLowerCase())) {
newValues.add(song);
}
}
}
filteredList.addAll(newValues);
//filteredList = newValues;
results.count = newValues.size();
}
return results;
}
#Override
protected void publishResults (CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
}
private static class ViewHolder{
TextView songName;
TextView artistName;
TextView songDuration;
ImageView thumbnail;
CardView cardView;
ImageView currentlyPlaying;
ViewHolder(View view){
songName = view.findViewById(R.id.songName);
thumbnail = view.findViewById(R.id.songThumbnail);
artistName = view.findViewById(R.id.artistName);
songDuration = view.findViewById(R.id.songDuration);
cardView = view.findViewById(R.id.cardView);
currentlyPlaying = view.findViewById(R.id.currentlyPlaying);
}
}
}
and
public void retrieveSongs() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Songs");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
List<Song> songsList = new ArrayList<>();
for (DataSnapshot ds : snapshot.getChildren()) {
Song song = ds.getValue(Song.class);
songsList.add(song);
jcAudios.add(JcAudio.createFromURL(song.getSongName(), song.getSongUrl()));
}
adapter = new ListAdapter(getApplicationContext(), songsList);
jcPlayerView.initPlaylist(jcAudios, null);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(MusicActivity.this, "FAILED!", Toast.LENGTH_SHORT).show();
}
});
}
Also its better to create one instance of adapter and swapData in retrieveSongs...
EDITED: Try something like this
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Song song = (Song)adapter.getItem(i)
jcPlayerView.playAudio(JcAudio.createFromURL(song.getSongName(), song.getSongUrl()));
jcPlayerView.setVisibility(View.VISIBLE);
jcPlayerView.createNotification();
adapter.notifyDataSetChanged();
}
});

Having trouble to showing videos in GridView layout?

I want to show my specific folder vedios in GridView layout.
But I am getting black items in GridView layout
Screenshot showing GridView layout
This is my class for getting data from internal memory.
public class Spacecraft {
String name;
boolean Checked=false;
private Uri uri;;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Uri getUri() {
return uri;
}
public void setUri(Uri uri) {
this.uri = uri;
}
public boolean isChecked(){
return Checked;
}
public void toggleChecked(){
Checked = !Checked;
}
}
This is my Adapter Class.
public class VedioAdapter extends BaseAdapter {
Context c;
ArrayList<Spacecraft> spacecrafts;
public VedioAdapter(Context c, ArrayList<Spacecraft> spacecrafts) {
this.c = c;
this.spacecrafts = spacecrafts;
}
#Override
public int getCount() {
return spacecrafts.size();
}
#Override
public Object getItem(int i) {
return spacecrafts.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view==null)
{
//INFLATE CUSTOM LAYOUT
view= LayoutInflater.from(c).inflate(R.layout.whatsapp_vedio,viewGroup,false);
}
final Spacecraft s= (Spacecraft) this.getItem(i);
if(s.isChecked()){
view.setBackgroundColor(Color.parseColor("#06ad94"));
}
else view.setBackgroundColor(Color.TRANSPARENT);
// TextView nameTxt= (TextView) view.findViewById(R.id.textView);
VideoView vedio=(VideoView)view.findViewById(R.id.vedio);
vedio.setVideoURI(s.getUri());
//BIND DATA
// nameTxt.setText(s.getName());
return view;
}
}
This is my VedioLayout activity class.
public class VedioGrid extends AppCompatActivity {
Spacecraft s;
ArrayList<Spacecraft> list = new ArrayList<>();
ArrayList<Spacecraft> list_items = new ArrayList<>();
int count = 0;
public ArrayList<Spacecraft> getPlayList(String rootPath) {
ArrayList<Spacecraft> fileList = new ArrayList<>();
try {
File rootFolder = new File(rootPath);
File[] files = rootFolder.listFiles(); //here you will get NPE if directory doesn't contains any file,handle it like this.
for (File file : files) {
if (file.isDirectory()) {
if (getPlayList(file.getAbsolutePath()) != null) {
fileList.addAll(getPlayList(file.getAbsolutePath()));
} else {
break;
}
} else if (file.getName().endsWith(".mp4")) {
s = new Spacecraft();
s.setName(file.getName());
s.setUri(Uri.fromFile(file));
fileList.add(s);
}
}
return fileList;
} catch (Exception e) {
return null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.images);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
String path = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/and/";
list = getPlayList(path);
GridView gv = (GridView) findViewById(R.id.simpleGridView);
final VedioAdapter adapter = new VedioAdapter(this, list);
gv.setAdapter(adapter);
gv.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
gv.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
Spacecraft s = list.get(position);
s.toggleChecked();
if (s.isChecked()) {
adapter.notifyDataSetChanged();
count = count + 1;
mode.setTitle(count + " Deleted Items");
list_items.add(s);
} else {
if (count != 0) {
adapter.notifyDataSetChanged();
count = count - 1;
mode.setTitle(count + " Deleted Items");
list_items.remove(s);
}
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
final ActionMode mod = mode;
switch (item.getItemId()) {
case R.id.action_open:
new AlertDialog.Builder(VedioGrid.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this image?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int p) {
int i;
for (i = 0; i < list_items.size(); ++i) {
Spacecraft s1 = list_items.get(i);
File f = new File(s1.getUri().getPath());
Boolean deleted = f.delete();
VedioGrid.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(s1.getUri().getPath()))));
if (deleted == true) {
list.remove(s1);
adapter.notifyDataSetChanged();
}
}
list_items.clear();
Toast.makeText(VedioGrid.this, count + "Deleted", Toast.LENGTH_SHORT).show();
count = 0;
mod.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.show();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Spacecraft s = list.get(position);
Toast.makeText(getApplicationContext(), s.getName(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
I am not getting the videos in layout and even if try to select multiple items the items nothing happens in the activity.
Am I doing wrong?
I am using
gv.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
gv.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener()
but nothing happens.
Earlier I tried this to fetch the images from internal memory I get the desired result and able to select the items but in this, I am using the same logic to fetch videos and show in GridView layout but not getting the result.
I get black items as shown in the above screenshot and not able to select.
Please help me.

Displaying images using custom ListView Filter in Android

I have created a list view in android and implemented custom filtering method, but images in the list view are not corresponding to text after using filter. This is because it filters only namesList list. I need to filter both namesList and imagesList at the same time. How do I do that?
public class MyCustomList extends ArrayAdapter<String> implements Filterable {
private final Activity context;
private List<String> filterList;
private List<String> namesList;
private List<String> imagesList;
public CustomList(Activity context,List<String> namesList, List<String> imagesList) {
super(context, R.layout.list_single, namesList);
this.context = context;
this.namesList = namesList;
this.imagesList = imagesList;
this.filterList= namesList;
}
#Override
public int getCount(){
return namesList.size();
}
#Override
public String getItem(int pos){
return namesList.get(pos);
}
#Override
public long getItemId(int pos){
return namesList.indexOf(getItem(pos));
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(namesList.get(position));
imageView.setImageResource(context.getResources().getIdentifier(imagesList.get(position), "drawable", context.getPackageName()));
return rowView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
namesList = (List<String>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
namesList = filterList;
FilterResults results = new FilterResults();
if(constraint != null && constraint.length()>0){
List<String> FilteredArrayNames = new ArrayList <String>();
constraint = constraint.toString().toLowerCase();
for (int i = 0; i <namesList.size(); i++) {
String dataNames = namesList.get(i);
if (dataNames.toLowerCase().contains(constraint.toString())) {
FilteredArrayNames.add(dataNames);
}
}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
Log.e("VALUES", results.values.toString());
} else {
results.count = namesList.size();
results.values = namesList;
}
return results;
}
};
return filter;
}
}
Modify your code with this:
List<String> FilteredArrayNames = new ArrayList <String>();
List<String> FilteredArrayImages = new ArrayList <String>();
constraint = constraint.toString().toLowerCase();
for (int i = 0; i <namesList.size(); i++) {
String dataNames = namesList.get(i);
String images = imagesList.get(i);
if (dataNames.toLowerCase().contains(constraint.toString())) {
FilteredArrayNames.add(dataNames);
FilteredArrayImages.add(images);
}
}
Then return this two List as a FilterResults object.
Try this example
Working for me
MainActivity
public class SearchActivity extends AppCompatActivity {
private ListView listView;
private MyAppAdapter myAppAdapter;
private ArrayList<Post> postArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listView = (ListView) findViewById(R.id.listView);
postArrayList = new ArrayList<>();
postArrayList.add(new Post("Dummy Title", "Dummy Sub Title"));
postArrayList.add(new Post("Searchview in actionbar", "enjoy search functionality from actionbar in android"));
postArrayList.add(new Post("Search in listview", "search feature that filter listview item"));
postArrayList.add(new Post("Android Search Bar", "adding search feature in toolbar using appcompat library"));
postArrayList.add(new Post("Android Studio SearchView example", "Android SearchView tutorial in android studio"));
postArrayList.add(new Post("Android Tutorial", "Get latest android material with simple solution"));
postArrayList.add(new Post("nkDroid tutorials", "A to Z Android tutorials at one place"));
myAppAdapter = new MyAppAdapter(postArrayList, SearchActivity.this);
listView.setAdapter(myAppAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
//*** setOnQueryTextFocusChangeListener ***
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String searchQuery) {
myAppAdapter.filter(searchQuery.toString().trim());
listView.invalidate();
return true;
}
});
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
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_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Adapter Example
public class MyAppAdapter extends BaseAdapter {
public class ViewHolder {
TextView txtTitle, txtSubTitle;
}
public List<Post> parkingList;
public Context context;
ArrayList<Post> arraylist;
public MyAppAdapter(List<Post> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<Post>();
arraylist.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.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) {
View rowView = convertView;
ViewHolder viewHolder;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.item_post, null);
// configure view holder
viewHolder = new ViewHolder();
viewHolder.txtTitle = (TextView) rowView.findViewById(R.id.title);
viewHolder.txtSubTitle = (TextView) rowView.findViewById(R.id.subtitle);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txtTitle.setText(parkingList.get(position).getPostTitle() + "");
viewHolder.txtSubTitle.setText(parkingList.get(position).getPostSubTitle() + "");
return rowView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
parkingList.clear();
if (charText.length() == 0) {
parkingList.addAll(arraylist);
} else {
for (Post postDetail : arraylist) {
if (charText.length() != 0 && postDetail.getPostTitle().toLowerCase(Locale.getDefault()).contains(charText)) {
parkingList.add(postDetail);
}
}
}
notifyDataSetChanged();
}
}
Post
public class Post {
private String postTitle;
private String postSubTitle;
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostSubTitle() {
return postSubTitle;
}
public void setPostSubTitle(String postSubTitle) {
this.postSubTitle = postSubTitle;
}
public Post(String postTitle, String postSubTitle) {
this.postTitle = postTitle;
this.postSubTitle = postSubTitle;
}
}

ExpandableRecyclerAdapter How to force item to move up while expanding an item

This is my ExpandableRecyclerAdapter adapter
public class MyAdapter extends ExpandableRecyclerAdapter<MyAdapter.ProductParentViewHolder, MyAdapter.ProductChildViewHolder> {
private LayoutInflater mInflater;
private Context context;
private List<? extends ParentListItem> mParentItemList;
public MyAdapter(Context context, List<ParentListItem> itemList) {
super(itemList);
mInflater = LayoutInflater.from(context);
this.context = context;
this.mParentItemList = itemList;
}
#Override
public ProductParentViewHolder onCreateParentViewHolder(ViewGroup viewGroup) {
View view = mInflater.inflate(R.layout.list_item_crime_parent, viewGroup, false);
return new ProductParentViewHolder(view);
}
#Override
public ProductChildViewHolder onCreateChildViewHolder(ViewGroup viewGroup) {
View view = mInflater.inflate(R.layout.list_item_crime_child, viewGroup, false);
return new ProductChildViewHolder(view);
}
#Override
public void onBindParentViewHolder(ProductParentViewHolder crimeParentViewHolder, int i, ParentListItem parentListItem) {
Product product = (Product) parentListItem;
crimeParentViewHolder.productName.setText(product.getBrandName() + " " + product.getProductName());
Glide.with(context)
.load(product.getProductImagePath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(crimeParentViewHolder.thumbnail);
}
#Override
public void onBindChildViewHolder(ProductChildViewHolder productChildViewHolder, int i, Object childListItem) {
final ProductVariant productVariant = (ProductVariant) childListItem;
productChildViewHolder.mCrimeDateText.setText(productVariant.getVariantName());
productChildViewHolder.variantMrp.setText(context.getString(R.string.positive_amount, productVariant.getMRP()));
productChildViewHolder.variantMrp.setPaintFlags(productChildViewHolder.variantMrp.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
productChildViewHolder.variantSellPrice.setText(context.getString(R.string.positive_amount, productVariant.getSellPrice()));
//productChildViewHolder.variantMrp.setText(productVariant.getMRP().toString());
//productChildViewHolder.variantSellPrice.setText(productVariant.getSellPrice().toString());
if (productVariant.getInCart() == 0) {
productChildViewHolder.btnProductDetailAddToCart.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailMinus.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailQty.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailPlus.setVisibility(View.GONE);
} else {
productChildViewHolder.btnProductDetailAddToCart.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailMinus.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailQty.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailPlus.setVisibility(View.VISIBLE);
}
int quantity = productVariant.getInCart();
productChildViewHolder.btnProductDetailQty.setText(Integer.toString(quantity));
productChildViewHolder.btnProductDetailAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(1);
//Utility.loadShoppingCartItems();
notifyDataSetChanged();
invalidateOptionsMenu();
//holder.db.addItem(new CartItem(1, productVariant.getProductID(), productVariant.getVariantID(), 1));
}
});
productChildViewHolder.btnProductDetailPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(1 + productVariant.getInCart());
notifyDataSetChanged();
invalidateOptionsMenu();
//if (productVariant.getInCart() > 0) {
//int count = holder.db.updateSingleRow(productVariant.getProductID(), productVariant.getVariantID(), productVariant.getInCart());
//}
}
});
productChildViewHolder.btnProductDetailMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(productVariant.getInCart() - 1);
notifyDataSetChanged();
invalidateOptionsMenu();
if (productVariant.getInCart() == 0) {
//int count = holder.db.deleteSingleRow(productVariant.getProductID(), productVariant.getVariantID());
} else if (productVariant.getInCart() > 0) {
//int count = holder.db.updateSingleRow(productVariant.getProductID(), productVariant.getVariantID(), productVariant.getInCart());
}
//Utility.displayToast(holder.db.getItemsCount() + "");
}
});
//crimeChildViewHolder.mCrimeSolvedCheckBox.setChecked(productVariant.isSolved());
}
public class ProductParentViewHolder extends ParentViewHolder {
private static final float INITIAL_POSITION = 0.0f;
private static final float ROTATED_POSITION = 180f;
private final boolean HONEYCOMB_AND_ABOVE = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
public TextView productName;
public ImageView thumbnail;
public ImageButton mParentDropDownArrow;
public ProductParentViewHolder(View itemView) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.productName);
thumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
// mParentDropDownArrow = (ImageButton) itemView.findViewById(R.id.parent_list_item_expand_arrow);
}
#SuppressLint("NewApi")
#Override
public void setExpanded(boolean expanded) {
super.setExpanded(expanded);
if (!HONEYCOMB_AND_ABOVE) {
return;
}
if (expanded) {
// mParentDropDownArrow.setRotation(ROTATED_POSITION);
} else {
// mParentDropDownArrow.setRotation(INITIAL_POSITION);
}
}
}
public class ProductChildViewHolder extends ChildViewHolder {
public TextView mCrimeDateText;
public TextView variantMrp;
public TextView variantSellPrice;
public Button btnProductDetailAddToCart, btnProductDetailPlus, btnProductDetailMinus;
public TextView btnProductDetailQty;
public ProductChildViewHolder(View itemView) {
super(itemView);
mCrimeDateText = (TextView) itemView.findViewById(R.id.variantName);
variantMrp = (TextView) itemView.findViewById(R.id.productVariantMrp);
variantSellPrice = (TextView) itemView.findViewById(R.id.productVariantSellPrice);
btnProductDetailAddToCart = (Button) itemView.findViewById(R.id.btnProductDetailAddToCart);
btnProductDetailPlus = (Button) itemView.findViewById(R.id.btnProductDetailPlus);
btnProductDetailMinus = (Button) itemView.findViewById(R.id.btnProductDetailMinus);
btnProductDetailQty = (TextView) itemView.findViewById(R.id.btnProductDetailQty);
}
}
}
When i am bottom of the page and click on item it expands, but exapnded child item doesn't shows to user because it is bottom in the screen.
I want to move that item up in the screen and show expanded items to user.
How can i do that?
You can simply use the method setSelectedGroup()
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
expandableListView.setSelectedGroup(groupPosition);
return true;
}
});
This will move the selected group to the top
EDIT
Finally I came out with a solution for your ExpandableRecyclerAdapter also. Simply put this method inside your adapter implementation. Also you will require the reference of the recyclerView inside the adapter which you can pass to the adapter at the time of initialization.
int lastPos = -1;
#Override
public void onParentListItemExpanded(int position) {
List<? extends ParentListItem> parentItemList = this.getParentItemList();
collapseAllParents();
int finalPos = position;
if (lastPos != -1 && lastPos < position) {
finalPos = position - parentItemList.get(lastPos).getChildItemList().size();
}
expandParent(finalPos);
mRecyclerView.smoothScrollToPosition(finalPos);
lastPos = position;
}
I found this issue at https://github.com/bignerdranch/expandable-recycler-view/issues/156 . Although the solution given there didn't work. Slight tweaking to that make it work.
Use this following code in your expandable listview click listener. Do something liket his
yourExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean onGroupClick(final ExpandableListView parent, View v, final int groupPosition, long id) {
....
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
parent.smoothScrollToPositionFromTop(groupPosition + 1, 0);
}
},100);
....
return true;
}
});
Use AnimatedExpandableListView

How to perform search in the expandable listview which is in the fragment?

Here is the thing..
I have one activity in which i have implmented the ActionBarSherlock,View Pager with Tab Navigation.
In Action Bar i have placed the search view.Now i am adding the list of fragments from the activity using viewPagerAdapter.
Now, In fragments i have placed the expandable listview and i am display the products with its section name in the expandable listview.
What i want to do ::
I want to perform the search of products from the expandable listview.
Problem which i have faced ::
I have placed the searchview in the Activity from which i am calling the different fragments.So how to perform the search ???
My code ::
Activity ::
public class Activity extends SherlockFragmentActivity implements TabListener,SearchView.OnQueryTextListener,SearchView.OnSuggestionListener
{
TabHost tabHost;
TabHost.TabSpec spec;
Intent intent;
Resources res;
Context mContext;
ProgressDialog pd=null;
Handler handler=new Handler();
MD5Generator md5Generator=new MD5Generator();
HttpConn httpConn=new HttpConn();
MyAccountInfo myAccountInfo;
private UserInfo userInfo=new UserInfo();
private Calendar cal = Calendar.getInstance();
private AppPreferences preference;
ArrayList<String> menuInfo;
//private ActionBar actionBar;
private ActionBarTabMenuAdapter actionbartabmenuAdapter;
private ViewPager awesomePager;
DataHelper dataHelper;
ArrayList<Integer> servicesImage;
ArrayList<String> servicesName;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ActionBar actionBar=getSupportActionBar();
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mContext=this;
// getSupportActionBar().setStackedBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.white)));
// getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// getSupportActionBar().setDisplayUseLogoEnabled(false);
// getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header_color)));
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
dataHelper=new DataHelper(this);
menuInfo=dataHelper.getTransMenuInfo();
servicesName = new ArrayList<String>();
servicesImage = new ArrayList<Integer>();
if(menuInfo.contains("1"))
{
servicesName.add(dataHelper.getTransMenu_ModuleName("1"));
servicesImage.add(R.drawable.abs__ic_search);
}
if(menuInfo.contains("2"))
{
servicesName.add(dataHelper.getTransMenu_ModuleName("2"));
servicesImage.add(R.drawable.abs__ic_search);
}
if(menuInfo.contains("4"))
{
servicesName.add(dataHelper.getTransMenu_ModuleName("4"));
servicesImage.add(R.drawable.abs__ic_search);
}
dataHelper.close();
servicesName.add("My Account");
servicesImage.add(R.drawable.abs__ic_search);
menuInfo.add("myacc");
servicesName.add("Reports");
servicesImage.add(R.drawable.abs__ic_search);
menuInfo.add("Reports");
servicesName.add("Settings");
servicesImage.add(R.drawable.abs__ic_search);
menuInfo.add("Settings");
List<Fragment> fragments = getFragments();
actionbartabmenuAdapter = new ActionBarTabMenuAdapter(getSupportFragmentManager(), fragments,this,servicesName,servicesImage);
awesomePager.setAdapter(actionbartabmenuAdapter);
System.out.println(" **** Selected Item==>"+awesomePager.getCurrentItem());
awesomePager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
for (int i = 0; i < actionbartabmenuAdapter.getCount(); i++) {
Tab tab = actionBar.newTab();
//tab.setText(awesomeAdapter.getPageTitle(i));
tab.setText(servicesName.get(i));
tab.setIcon(servicesImage.get(i));
tab.setTabListener(this);
actionBar.addTab(tab);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//Code Comes here...
System.out.println("Key Event:"+event.getAction()+",keyCode"+keyCode);
onBackPressed();
return true;
}
private List<Fragment> getFragments()
{
List<Fragment> fList = new ArrayList<Fragment>();
if(menuInfo.contains("1"))
{
fList.add(TopUpFragment.newInstance(this,"Topup"));
}
if(menuInfo.contains("2"))
{
fList.add(BillPayFragment.newInstance(this,"Billpay"));
}
if(menuInfo.contains("4"))
{
fList.add(VoucherFragment.newInstance(this,"Voucher Sell"));
}
fList.add(MyAccountFragment.newInstance(this,"My Account"));
fList.add(ReportFragment.newInstance(this,"Reports"));
fList.add(SettingsListFragment.newInstance(this,"Settings"));
return fList;
}
#Override
public void onBackPressed()
{
new AlertDialog.Builder(ButtonPayActivity.this)
.setTitle( "Exit Application" )
.setMessage( "Are you sure you want to Exit" )
.setPositiveButton("YES", new android.content.DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//do stuff onclick of YES
finish();
}
})
.setNegativeButton("NO", new android.content.DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//do stuff onclick of CANCEL
arg0.dismiss();
}
}).show();
}
public static View prepareTabView(Context context, String text,int resId) {
View view = LayoutInflater.from(context).inflate(
R.layout.custom_tabview, null);
ImageView iv = (ImageView) view.findViewById(R.id.iv_tabimage);
iv.setImageResource(resId);
TextView tv = (TextView) view.findViewById(R.id.tabIndicatorTextView);
tv.setText(text);
return view;
}
private class ActionBarTabMenuAdapter extends FragmentPagerAdapter {
Activity context;
Context ctx;
ArrayList<String> menuInfo;
private List<Fragment> fragments;
ArrayList<String> services;
ArrayList<Integer> images;
public ActionBarTabMenuAdapter(FragmentManager fm, List<Fragment> fragments,Context ctx,ArrayList<String> servicesName,ArrayList<Integer> servicesImage)
{
super(fm);
this.context=(Activity) ctx;
dataHelper=new DataHelper(ctx);
menuInfo=dataHelper.getTransMenuInfo();
dataHelper.close();
this.services = servicesName;
this.images = servicesImage;
this.fragments = fragments;
menuInfo.add("My Account");
menuInfo.add("Reports");
menuInfo.add("Settings");
System.out.println("## Ctx in ButtonPay==>"+this.context);
}
#Override
public int getCount()
{
return menuInfo.size();
}
#Override
public Fragment getItem(int position) {
System.out.println("position of fragment--"+position);
return this.fragments.get(position);
}
}
class ViewHolder {
TextView Title, Description, ReadMore;
}
public void onClick(View v) {
}
#Override
public void onTabReselected(Tab tabposition, FragmentTransaction fragmentposition) {
System.out.println("Tab Reselected method");
}
#Override
public void onTabSelected(Tab tabposition, FragmentTransaction fragmentposition) {
awesomePager.setCurrentItem(tabposition.getPosition());
}
#Override
public void onTabUnselected(Tab tabposition, FragmentTransaction fragmentposition) {
System.out.println("Tab unselected method");
System.out.println("tab posiiton in unselected method---"+tabposition.getPosition());
System.out.println("fragment position in unselected method---"+tabposition);
}
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
getSupportMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_item_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search for Products");
searchView.setOnQueryTextListener(this);
searchView.setOnSuggestionListener(this);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(this, "You searched for: " + query, Toast.LENGTH_LONG).show();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onSuggestionSelect(int position) {
return false;
}
#Override
public boolean onSuggestionClick(int position) {
Toast.makeText(this, "Suggestion clicked: ",Toast.LENGTH_LONG).show();
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menu_Home:
startActivityForResult(new Intent(ButtonPayActivity.this,ButtonPayActivity.class), 11);
break;
case R.id.menu_favourite:
finish();
startActivityForResult(new Intent(ButtonPayActivity.this,FavouriteMenuActivity.class), 11);
break;
case R.id.menu_Balance:
new Thread(new GetBalanceInfoRunnable(mContext)).start();
break;
case R.id.menu_logout:
new AlertDialog.Builder(ButtonPayActivity.this)
.setTitle( "Exit Application")
.setMessage( "Are you sure you want to Logout?")
.setPositiveButton("YES", new android.content.DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//do stuff onclick of YES
setResult(2);
finish();
}
})
.setNegativeButton("NO", new android.content.DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//do stuff onclick of CANCEL
arg0.dismiss();
}
}).show();
break;
}
return super.onOptionsItemSelected(item);
}
}
Fragment ::
public class TopUpFragment extends SherlockFragment
{
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
LinkedHashMap<String,String>listHeader;
ArrayList<String> topupProSectionID;
ArrayList<String> topupProSectionsName;
ArrayList<TopupProSectionName.Products> listDataChild;
static Context ctx;
static TopUpFragment f ;
private DataHelper dataHelper;
private int lastExpandedPosition = -1;
private ArrayList<TopupProSectionName> mTopupGroupCollection;
public static TopUpFragment newInstance(Activity context,String string)
{
f = new TopUpFragment();
ctx=context;
System.out.println("$$$ onNewInst==>"+ctx);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
//String message = getArguments().getString(EXTRA_MESSAGE);
View v = inflater.inflate(R.layout.myfragment_layout, container, false);
//TextView messageTextView = (TextView)v.findViewById(R.id.textView);
//messageTextView.setText(message);
expListView = (ExpandableListView)v.findViewById(R.id.lvExp);
prepareListData();
System.out.println("%%% Ctx==>"+ctx);
return v;
}
private void prepareListData()
{
listHeader = new LinkedHashMap<String, String>();
dataHelper=new DataHelper(ctx);
topupProSectionID=new ArrayList<String>();
listHeader = dataHelper.getSectionSForTopupProduct();
if (listHeader != null)
{
Map.Entry me = null;
Set entrySet = listHeader.entrySet();
Iterator i = entrySet.iterator();
mTopupGroupCollection = new ArrayList<TopupProSectionName>();
TopupProSectionName sectionName = null;
TopupProSectionName.Products topupProduct = null;
while (i.hasNext())
{
sectionName = new TopupProSectionName();
me = (Map.Entry)i.next();
System.out.print("-->"+me.getKey() + ": ");
System.out.println(me.getValue());
sectionName.setsectionName((String)me.getKey());
listDataChild=new ArrayList<TopupProSectionName.Products>();
listDataChild=dataHelper.getFlexiProducts(me.getValue().toString());
listDataChild=dataHelper.getFixProducts(me.getValue().toString(),listDataChild);
System.out.println("Getting products for sys ser ID:"+me.getValue().toString());
//billpayProSectionsName.add((String) me.getKey());
topupProSectionID.add((String) me.getValue());
for(int index=0;index<listDataChild.size();index++)
{
topupProduct = sectionName.new Products();
if(listDataChild.get(index).getSystemServiceID().equals(me.getValue()))
{
topupProduct.setProductName(listDataChild.get(index).getProductName());
topupProduct.setProductID(listDataChild.get(index).getProductID());
sectionName.topupProductList.add(topupProduct);
}
}
mTopupGroupCollection.add(sectionName);
}
}
dataHelper.close();
listAdapter = new ExpandableListAdapter(ctx,mTopupGroupCollection,expListView);
expListView.setAdapter(listAdapter);
}
class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private ArrayList<TopupProSectionName> listDataHeader; // header titles
ArrayList<TopupProSectionName.Products> topupProducts;
private int[] groupStatus;
private ExpandableListView mExpandableListView;
public ExpandableListAdapter(Context context,
ArrayList<TopupProSectionName>sectionName,ExpandableListView pExpandableListView)
{
this._context = context;
this.listDataHeader = sectionName;
this.topupProducts = listDataChild;
mExpandableListView = pExpandableListView;
groupStatus = new int[listDataHeader.size()];
setListEvent();
}
private void setListEvent()
{
mExpandableListView.setOnGroupExpandListener(new OnGroupExpandListener()
{
public void onGroupExpand(int groupPosition)
{
//collapse the old expanded group, if not the same as new group to expand
//groupStatus[position] = 1;
if (lastExpandedPosition != -1 && groupPosition != lastExpandedPosition)
{
mExpandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
/*mExpandableListView.setOnGroupCollapseListener(new OnGroupCollapseListener()
{
#Override
public void onGroupCollapse(int position)
{
groupStatus[position] = 0;
}
});*/
mExpandableListView.setOnChildClickListener(new OnChildClickListener()
{
#Override
public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id)
{
String ID=listDataHeader.get(groupPosition).topupProductList.get(childPosition).getProductID();
System.out.println("Product ID in Adapter==>"+ID);
return true;
}
});
}
#Override
public String getChild(int groupPosition, int childPosititon) {
return listDataHeader.get(groupPosition).topupProductList.get(childPosititon).getProductName();
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ChildHolder childHolder;
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item_fragment, null);
childHolder = new ChildHolder();
childHolder.title = (TextView) convertView.findViewById(R.id.lblListItem);
convertView.setTag(childHolder);
}
else
{
childHolder = (ChildHolder) convertView.getTag();
}
childHolder.title.setText(mTopupGroupCollection.get(groupPosition).topupProductList.get(childPosition).getProductName());
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return mTopupGroupCollection.get(groupPosition).topupProductList.size();
}
#Override
public Object getGroup(int groupPosition) {
return mTopupGroupCollection.get(groupPosition);
}
#Override
public int getGroupCount() {
return mTopupGroupCollection.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent)
{
GroupHolder groupHolder;
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
groupHolder = new GroupHolder();
groupHolder.title = (TextView) convertView.findViewById(R.id.lblListHeader);
convertView.setTag(groupHolder);
}
else
{
groupHolder = (GroupHolder) convertView.getTag();
}
groupHolder.title.setTypeface(null, Typeface.BOLD);
groupHolder.title.setText(mTopupGroupCollection.get(groupPosition).getsectionName());
return convertView;
}
class GroupHolder {
TextView title;
}
class ChildHolder {
TextView title;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
I am actually getting the action bar in wrong way.
TO use the action bar in each fragment ::
i have placed the setHasOptionsMenu(true); in my onCreate() of fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
After that i am able to use the onCreateOptionMenu() in which i placed the searchview and now i am able to search the date from the expandable listview,getting text from searchview.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu, menu);
final MenuItem searchItem = menu.findItem(R.id.menu_item_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search Here");
}
And now m done,Problem resolved.... ;)

Categories

Resources