在設計app的過程中, 不免都會碰到listview這個android元件,
今天介紹cardslib + ListViewAnimations這兩個libraries來取代陽春的listview, 並做簡單的使用
cardslib: 先到https://github.com/gabrielemariotti/cardslib 把zip檔載下來(或用git clone git:// github.com/gabrielemariotti/cardslib) 把zip檔解壓到和app project同一層目錄底下(重要!否則Eclipse有時候會搜不到)
ListViewAnimations: ListViewAnimations更新版本速度太快, 因此這裡用的是比較舊版本的2.6.0用來和cardslib相容(可使用git reset 退版本), 也是一樣先把zip檔解壓到和app project同個目錄 (中間也有include android-support-v7-appcompat, 有需要可以用SDK Manager下載)
接著打開Eclipse, 把剛剛的library 以Files -> import的方式import近來,
之後在java folder的地方, 按右鍵選擇 Build path -> Use as source folder
然後在兩個library project的右鍵->properties 勾選Is Library
回到app project,
在layout的xml, 新增CardListView
<it.gmariotti.cardslib.library.view.CardListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/carddemo_list_gplaycard"
card:list_card_layout_resourceID="@layout/list_card_thumbnail_layout" />
並且在Layout的attributes增加一行
xmlns:card="http://schemas.android.com/apk/res-auto"
接著在fragment java底下新增一個GooglePlaySmallCard class定義每個List item的物件, 並且在onActivityCreated的callback裡面做初始化cards的動作
最後設定AlphaAdapter:
private void setAlphaAdapter(CardListView mListView, CardArrayAdapter mCardArrayAdapter) {
AnimationAdapter animCardArrayAdapter = new AlphaInAnimationAdapter(mCardArrayAdapter);
animCardArrayAdapter.setAbsListView(mListView);
if (mListView != null) {
mListView.setExternalAdapter(animCardArrayAdapter,mCardArrayAdapter);
}
}
就可以看到有漸層顯示的Listview囉!
完整java檔如下:
package com.diousk.hellobalabala;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.internal.CardThumbnail;
import it.gmariotti.cardslib.library.view.CardListView;
import java.util.ArrayList;
import java.util.Locale;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.nhaarman.listviewanimations.swinginadapters.AnimationAdapter;
import com.nhaarman.listviewanimations.swinginadapters.prepared.AlphaInAnimationAdapter;
public class HelloTabEntryActivity extends ActionBarActivity implements
ActionBar.TabListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {@link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_tab_entry);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hello_tab_entry, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
// below).
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_hello_tab_entry,
container, false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d("PlaceholderFragment", "onActivityCreated " + this.getArguments().getInt(ARG_SECTION_NUMBER));
super.onActivityCreated(savedInstanceState);
if (1 == this.getArguments().getInt(ARG_SECTION_NUMBER)){
initCards();
}
}
private void initCards() {
//Init an array of Cards
ArrayList<Card> cards = new ArrayList<Card>();
for (int i=0;i<20;i++){
GooglePlaySmallCard card = new GooglePlaySmallCard(this.getActivity());
card.setTitle("Application example "+i);
card.setSecondaryTitle("A company inc..."+i);
card.setRating((float)(Math.random()*(5.0)));
card.count=i;
card.init();
cards.add(card);
}
CardArrayAdapter cardArrayAdapter = new CardArrayAdapter(getActivity(),cards);
CardListView listView = (CardListView) getActivity().findViewById(R.id.carddemo_list_gplaycard);
setAlphaAdapter(listView, cardArrayAdapter);
}
private void setAlphaAdapter(CardListView mListView, CardArrayAdapter mCardArrayAdapter) {
AnimationAdapter animCardArrayAdapter = new AlphaInAnimationAdapter(mCardArrayAdapter);
animCardArrayAdapter.setAbsListView(mListView);
if (mListView != null) {
mListView.setExternalAdapter(animCardArrayAdapter,mCardArrayAdapter);
}
}
public class GooglePlaySmallCard extends Card {
protected TextView mTitle;
protected TextView mSecondaryTitle;
protected RatingBar mRatingBar;
protected int resourceIdThumbnail;
protected int count;
protected String title;
protected String secondaryTitle;
protected float rating;
public GooglePlaySmallCard(Context context) {
this(context, R.layout.carddemo_mycard_inner_content);
}
public GooglePlaySmallCard(Context context, int innerLayout) {
super(context, innerLayout);
//init();
}
private void init() {
//Add thumbnail
CardThumbnail cardThumbnail = new CardThumbnail(mContext);
if (resourceIdThumbnail==0)
cardThumbnail.setDrawableResource(R.drawable.ic_launcher);
else{
cardThumbnail.setDrawableResource(resourceIdThumbnail);
}
addCardThumbnail(cardThumbnail);
//Only for test, some cards have different clickListeners
if (count==12){
setTitle(title + " No Click");
setClickable(false);
}else if (count==20){
setTitle(title + " Partial Click");
addPartialOnClickListener(Card.CLICK_LISTENER_CONTENT_VIEW,new OnCardClickListener() {
@Override
public void onClick(Card card, View view) {
Toast.makeText(getContext(), "Partial click Listener card=" + title, Toast.LENGTH_SHORT).show();
}
});
}else{
//Add ClickListener
setOnClickListener(new OnCardClickListener() {
@Override
public void onClick(Card card, View view) {
Toast.makeText(getContext(), "Click Listener card=" + title, Toast.LENGTH_SHORT).show();
}
});
}
//Swipe
if (count>5 && count<13){
setTitle(title + " Swipe enabled");
setSwipeable(true);
setOnSwipeListener(new OnSwipeListener() {
@Override
public void onSwipe(Card card) {
Toast.makeText(getContext(), "Removed card=" + title, Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void setupInnerViewElements(ViewGroup parent, View view) {
//Retrieve elements
mTitle = (TextView) parent.findViewById(R.id.carddemo_myapps_main_inner_title);
mSecondaryTitle = (TextView) parent.findViewById(R.id.carddemo_myapps_main_inner_secondaryTitle);
mRatingBar = (RatingBar) parent.findViewById(R.id.carddemo_myapps_main_inner_ratingBar);
if (mTitle != null)
mTitle.setText(title);
if (mSecondaryTitle != null)
mSecondaryTitle.setText(secondaryTitle);
if (mRatingBar != null) {
mRatingBar.setNumStars(5);
mRatingBar.setMax(5);
mRatingBar.setStepSize(0.5f);
mRatingBar.setRating(rating);
}
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSecondaryTitle() {
return secondaryTitle;
}
public void setSecondaryTitle(String secondaryTitle) {
this.secondaryTitle = secondaryTitle;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public int getResourceIdThumbnail() {
return resourceIdThumbnail;
}
public void setResourceIdThumbnail(int resourceIdThumbnail) {
this.resourceIdThumbnail = resourceIdThumbnail;
}
}
}
}
P.S. 1. 基本上只要把cardslib/ListViewAnimations project載下來裡面就有不少demo sample可以參考