Friday, 22 May 2015

Swipable Tabs changing app icon as well as tab icon


SongGalleryActivity .java

package com.mtag;

import com.util.NotificationPanel;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

@SuppressLint("NewApi")
public class SongGalleryActivity extends FragmentActivity  implements
ActionBar.TabListener {
int backButtonCount=0;
private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private android.app.ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "Genres", "Artists", "Albums","Songs","PlayLists" };
 
    private static final int[] ICONS = new int[] {
        R.drawable.genre_inactive,
        R.drawable.artist_inactive,
        R.drawable.albums_inactive,
        R.drawable.songs_inactive,
        R.drawable.lists_inactive,
};

    private static final int[] ICONS_SELECTED = new int[] {
        R.drawable.genre_active,
        R.drawable.artist_active,
        R.drawable.albums_active,
        R.drawable.songs_active,
        R.drawable.lists_active,
};
 
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song_gallery);

String val=getIntent().getStringExtra("DO");
Log.d("value..............", "::::"+val);

// Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);    
        LayoutInflater mInflater = LayoutInflater.from(this);
        View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
        actionBar.setCustomView(mCustomView);
        actionBar.setDisplayShowCustomEnabled(true);

/*     // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }*/
     
        // instead of NewsFeedActivity you have to use your activity name here
        for (int i=0; i < tabs.length; i++)
                {
                actionBar.addTab(actionBar.newTab().setText(tabs[i])
                                         .setIcon(SongGalleryActivity.this.getResources().getDrawable(ICONS[i]))
                                         .setTabListener(this));
                }//endfor
     
        actionBar.setStackedBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.white)));
     
       //actionBar.setStackedBackgroundDrawable(getResources().getDrawable(R.color.white));
     
        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
 //actionBar.setIcon(ICONS_SELECTED[position]);// this is for changing logo in the applcation also
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
     
}

@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub

}

@SuppressLint("NewApi")
@Override
public void onTabSelected(Tab tab, FragmentTransaction arg1) {
viewPager.setCurrentItem(tab.getPosition());
tab.setIcon(ICONS_SELECTED[tab.getPosition()]);
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction arg1) {
tab.setIcon(ICONS[tab.getPosition()]);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}

@Override
public void onBackPressed() {

if(backButtonCount >= 1)
   {

NotificationPanel notificationPanel=new NotificationPanel(this);
notificationPanel.notificationCancel();

       Intent intent = new Intent(Intent.ACTION_MAIN);
       intent.addCategory(Intent.CATEGORY_HOME);
       intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       startActivity(intent);
   }
   else
   {
       Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
       backButtonCount++;
   }
}
}


Note :

actionBar.setIcon(ICONS_SELECTED[position]);// this is for changing logo in the applcation also


if u add this 

   public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
               actionBar.setIcon(ICONS_SELECTED[position]);
            }

the application icon also will changed 




TabsPagerAdapter .java


package com.mtag;

import com.viewpagerindicator.IconPagerAdapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class TabsPagerAdapter extends FragmentPagerAdapter implements IconPagerAdapter {


public TabsPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}

@Override
public Fragment getItem(int index) {
switch (index) {
        case 0:
            // Genres fragment activity
            return new GenresFragment();
        case 1:
            // Artist fragment activity
            return new ArtistsFragment();
        case 2:
            // ALbum fragment activity
            return new AlbumsFragment();
     
        case 4:
            // Playlist fragment activity
            return new PlaylistFragment();
        case 3:
            // ALbum fragment activity
            return new SongsFragment();
        }

        return null;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return 5;
}

@Override
public int getIconResIdNormal(int index) {
// TODO Auto-generated method stub
return 0;
}

@Override
public int getIconResIdSelected(int index) {
// TODO Auto-generated method stub
return 0;
}

@Override
public int getBackgroundResIdSelected(int index) {
// TODO Auto-generated method stub
return 0;
}

@Override
public int getBackgroundResIdNormal(int index) {
// TODO Auto-generated method stub
return 0;
}



}


fragment

package com.mtag;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Set;

import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.source.Song;
import com.util.NotificationPanel;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class SongsFragment extends Fragment{

LayoutInflater inflater;
ListView listView;
View rootView;
private ArrayList<Song> songList;
ArtistsAdapter adapter;
MediaPlayer mediaPlayer;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflater=inflater;
View rootView = inflater.inflate(R.layout.fragment_songs, container, false);     
this.rootView=rootView;
this.inflater=inflater;
GUI();
       return rootView;
}

private void GUI() {
String val=getActivity().getIntent().getStringExtra("DO");
Log.d("value..............", "::::"+val);
listView=(ListView)rootView.findViewById(R.id.listViewSongs);
songList = new ArrayList<Song>();
//get songs from device
getSongList();
//sort alphabetically by title
Collections.sort(songList, new Comparator<Song>(){
public int compare(Song a, Song b){
return a.getTitle().compareTo(b.getTitle());
}
});
fillAdapter();
//create and set adapter
/*com.source.SongAdapter adapter=new com.source.SongAdapter(getActivity(), songList);
listView.setAdapter(adapter);*/
}
private void fillAdapter() {
if(null != songList || songList.size() > 0){
adapter=new ArtistsAdapter(getActivity());
listView.setAdapter(adapter);
}
}
class ArtistsAdapter extends ArrayAdapter implements SectionIndexer{
Context context;
HashMap<String, Integer> alphaIndexer;
       String[] sections;
public ArtistsAdapter(Context context) {
super(context, R.layout.row_song_song, songList);
this.context = context;
alphaIndexer = new HashMap<String, Integer>();
           int size = songList.size();
 
           for (int x = 0; x < size; x++) {
               Song s = songList.get(x);
 
// get the first letter of the store
               String ch =  s.getAlbum().substring(0, 1);
// convert to uppercase otherwise lowercase a -z will be sorted after upper A-Z
               ch = ch.toUpperCase();
 
// HashMap will prevent duplicates
               alphaIndexer.put(ch, x);
           }
 
           Set<String> sectionLetters = alphaIndexer.keySet();
 
   // create a list from the set to sort
           ArrayList<String> sectionList = new ArrayList<String>(sectionLetters); 
 
           Collections.sort(sectionList);
 
           sections = new String[sectionList.size()];
 
           sectionList.toArray(sections);
}
@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final Holder holder;
if (convertView == null) {
holder = new Holder();
convertView = (LinearLayout) LayoutInflater.from(context)
.inflate(R.layout.row_song_song, null);
holder.texSongName=(TextView)convertView.findViewById(R.id.song_title);
holder.textSongDetail=(TextView)convertView.findViewById(R.id.song_data);
holder.layout=(LinearLayout)convertView.findViewById(R.id.song_layout);
convertView.setTag(holder);

} else {
holder = (Holder) convertView.getTag();
}
holder.layout.setTag(songList.get(position).getData());
holder.texSongName.setText(songList.get(position).getTitle());
holder.textSongDetail.setText(songList.get(position).getArtist());
//holder.texSongName.setTag(songList.get(position).getData());
holder.layout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
play(v.getTag().toString());
// Log.d("id", ":"+v.getId());
Toast.makeText(getContext(), "clicked"+v.getTag().toString(), Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
class Holder{
TextView texSongName,textSongDetail;
LinearLayout layout;
}

@Override
public Object[] getSections() {
// TODO Auto-generated method stub
return sections;
}

public int getPositionForSection(int section) {
          return alphaIndexer.get(sections[section]);
      }

@Override
public int getSectionForPosition(int position) {
// TODO Auto-generated method stub
return 1;
}
}
int count=0;
String playFile;
private void play(String path) {
count++;
playFile=path;
//showNotification();
new NotificationPanel(getActivity());
if(mediaPlayer!=null && mediaPlayer.isPlaying()){
Log.d("*****begin*****", "playing");
stopPlaying();
Log.d("*****begin*****", "stoping");
     } else{
    Log.d("*****begin*****", "nothing");
     }

Uri myUri1 = Uri.parse(path);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getActivity(), myUri1);
} catch (IllegalArgumentException e) {
            Toast.makeText(getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (SecurityException e) {
            Toast.makeText(getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IllegalStateException e) {
            Toast.makeText(getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
try {
mediaPlayer.prepare();
        } catch (IllegalStateException e) {
            Toast.makeText(getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(getActivity(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        }
        mediaPlayer.start();
   
}
private void stopPlaying() { 
        if (mediaPlayer != null) {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
       } 
    } 

//method to retrieve song info from deviceyyyy
public void getSongList(){
//query external audio
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
//iterate over results if valid
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
int albumColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ALBUM);
int trackColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TRACK);
int dataColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.DATA);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
String thisAlbum = musicCursor.getString(albumColumn);
String thisTrack = musicCursor.getString(trackColumn);
String thisData = musicCursor.getString(dataColumn);
songList.add(new Song(thisId, thisTitle, thisArtist,thisAlbum,thisTrack,thisData));

while (musicCursor.moveToNext());
}
}
}





No comments:

Post a Comment