2013-12-09 3 views
0

У меня есть ListView, что его содержимое заполняется с удаленного сервера. Это простой ListView, созданный следующими учебниками, которые вы обычно находите в блогах. Недавно я узнал ListViewAnimation и хотел бы использовать его в своем проекте.Android - Как реализовать ListViewAnimation для существующего ListView?

У меня уже есть Listview, теперь как реализовать библиотеку listviewanimation в существующем?

Я попытался следовать за wiki на github, но все равно не смог пройти через него.

Вот моя ListView активность:

public class CategoryActivity extends ListActivity { 
    public void onCreate(Bundle savedInstanceState) { 
     setContentView(R.layout.activity_category); 

     ListView lv = getListView(); 


     lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> arg0, View view, 
        int arg2, long arg3) { 

       // when item is clicked, go to its corresponding details 
       Intent i = new Intent(getApplicationContext(), 
         ItemListActivity.class); 
       String category_id = ((TextView) view 
         .findViewById(R.id.category_id)).getText() 
         .toString(); 
       i.putExtra("category_id", category_id); 
       startActivity(i); 
      } 
     }); 

     new LoadCategories().execute(); 
    } 

    class LoadCategories extends AsyncTask<String, String, String> { 

     @Override 
     protected String doInBackground(String... args) { 
      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 

      // getting JSON string from URL 
      String json = jsonParser.makeHttpRequest(Constants.URL_CATEGORY, "GET", 
        params); 

      // Check your log cat for JSON reponse 
      Log.d("Categories JSON: ", "> " + json); 

      try { 
       categories = new JSONArray(json); 

       if (categories != null) { 
        // looping through All albums 
        for (int i = 0; i < categories.length(); i++) { 
         JSONObject c = categories.getJSONObject(i); 

         // Storing each json item values in variable 
         String id = c.getString(TAG_ID); 
         String name = c.getString(TAG_NAME); 
         String songs_count = c.getString(TAG_CATEGORIES_COUNT); 

         // creating new HashMap 
         HashMap<String, String> map = new HashMap<String, String>(); 

         // adding each child node to HashMap key => value 
         map.put(TAG_ID, id); 
         map.put(TAG_NAME, name); 
         map.put(TAG_CATEGORIES_COUNT, songs_count); 

         // adding HashList to ArrayList 
         categoryList.add(map); 
        } 
       } else { 
        Log.d("Categories: ", "null"); 
       } 

      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return null; 
     } 


     @Override 
     protected void onPostExecute(String file_url) { 
      runOnUiThread(new Runnable() { 
       public void run() { 

        // populate each row with json data 
        ListAdapter adapter = new SimpleAdapter(
          CategoryActivity.this, categoryList, 
          R.layout.custom_list_category, new String[] { 
            TAG_ID, TAG_NAME, TAG_CATEGORIES_COUNT }, 
          new int[] { R.id.category_id, R.id.category_name, 
            R.id.songs_count }); 

        setListAdapter(adapter); 
       } 
      }); 
     } 
    } 

} 

Это layout.xml для деятельности:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <ListView 
     android:id="@android:id/list" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:cacheColorHint="#00000000" 
     android:dividerHeight="15dp" 
     android:footerDividersEnabled="true" 
     android:headerDividersEnabled="true" /> 
</LinearLayout> 

Как вы можете видеть в коде, список настраивается и заполняется по SimpleAdapter ,

Может ли кто-нибудь помочь мне в реализации библиотеки ListViewAnimation в моем проекте?


EDIT

Вот мой новый ListActivity. Я изменил часть AsyncTask onPostExecute. Сейчас проблема не показывает ничего. Просто пустой экран:

public class CategoryActivity extends ListActivity { 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

      setContentView(R.layout.activity_category); 


      // Check toast which user is logged in 
      userDetails = db.getUserDetails().get("name").toString(); 

      setTitle(userDetails); 

      // Hashmap for ListView 
      categoryList = new ArrayList<HashMap<String, String>>(); 

      new LoadCategories().execute(); 

      // get listview 
      ListView lv = getListView(); 

      //lv = (ListView) findViewById(R.id.category_list); 
      lv.setDivider(null); 

      lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> arg0, View view, 
         int arg2, long arg3) { 
        Intent i = new Intent(getApplicationContext(), 
          ItemListActivity.class); 

        String category_id = ((TextView) view 
          .findViewById(R.id.category_id)).getText() 
          .toString(); 
        i.putExtra("category_id", category_id); 

        startActivity(i); 
       } 
      }); 
    } 

    class LoadCategories extends AsyncTask<String, String, String> { 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(CategoryActivity.this); 
      pDialog.setMessage("Listing Categories..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 

     @Override 
     protected String doInBackground(String... args) { 
      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 

      // getting JSON string from URL 
      String json = jsonParser.makeHttpRequest(Constants.URL_CATEGORY, "GET", 
        params); 

      // Check your log cat for JSON reponse 
      Log.d("Categories JSON: ", "> " + json); 

      return json; 
     } 

     @Override 
     protected void onPostExecute(String json) { 
      try { 
       categories = new JSONArray(json); 

       if (categories != null) { 
        // looping through All albums 
        for (int i = 0; i < categories.length(); i++) { 
         JSONObject c = categories.getJSONObject(i); 

         // Storing each json item values in variable 
         String id = c.getString(TAG_ID); 
         String name = c.getString(TAG_NAME); 
         String songs_count = c.getString(TAG_CATEGORIES_COUNT); 

         // creating new HashMap 
         HashMap<String, String> map = new HashMap<String, String>(); 

         // adding each child node to HashMap key => value 
         map.put(TAG_ID, id); 
         map.put(TAG_NAME, name); 
         map.put(TAG_CATEGORIES_COUNT, songs_count); 

         // adding HashList to ArrayList 
         categoryList.add(map); 
        } 

        mAdapter = new CategoryListAdapter(CategoryActivity.this, categoryList); 
        AnimationAdapter animAdapter = new AlphaInAnimationAdapter(mAdapter); 
        animAdapter.setAbsListView(getListView()); 
        getListView().setAdapter(animAdapter); 

        // dismiss the dialog after getting all albums 
        pDialog.dismiss(); 
       } else { 
        Log.d("Categories: ", "null"); 
       } 

      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

} 

CategoryListAdapter класс:

public class CategoryListAdapter extends ArrayAdapter<HashMap<String, String>>{ 
     private Context mContext; 
     LayoutInflater inflater; 
     private final ArrayList<HashMap<String, String>> urls; 
     HashMap<String, String> resultp = new HashMap<String, String>(); 

     public CategoryListAdapter(Context context, ArrayList<HashMap<String, String>> items) { 
      /*super(items); 
      mContext = context;*/ 
      this.mContext = context; 

      urls = items; 
     } 

     @Override 
     public long getItemId(int position) { 
      return getItem(position).hashCode(); 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      TextView item_name; 
      TextView item_count; 
      TextView item_id; 

      inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

      View view = inflater.inflate(R.layout.custom_list_category, parent, false); 

      resultp = urls.get(position); 

      item_name = (TextView) view.findViewById(R.id.category_name); 
      item_count = (TextView) view.findViewById(R.id.songs_count); 
      item_id = (TextView) view.findViewById(R.id.category_id); 

      item_name.setText(resultp.get(CategoryActivity.TAG_NAME)); 
      item_count.setText(resultp.get(CategoryActivity.TAG_CATEGORIES_COUNT)); 
      item_id.setText(resultp.get(CategoryActivity.TAG_ID)); 

      return view; 
     } 
} 
+0

Какое свойство библиотеки вы хотите использовать? – keshav

+0

Вы имеете в виду, какая анимация? В частности, список альфа-адаптеров. – AimanB

+0

Проверьте мой второй ответ .. и дайте мне знать, если что-то еще потребуется. – keshav

ответ

1

Вы также можете попробовать настроить макет анимации на существующий вид списка. Для экс:

AnimationSet set = new AnimationSet(true); 
Animation animation = AnimationUtils.loadAnimation(getContext(), 
      R.anim.fadeout); 
set.addAnimation(animation); 
LayoutAnimationController controller = new LayoutAnimationController(
     set, 0.5f); 
<Your_list_view>.setLayoutAnimation(controller); 

Это позволит установить R.anim.fadeout анимацию к каждому элементу списка.

EDIT Попробуйте эту

Сохранить эту XML в папке Anim (это подается в действие)

<?xml version="1.0" encoding="UTF-8"?> 
<set xmlns:android="http://schemas.android.com/apk/res/android" > 

    <alpha 
     android:duration="500" 
     android:fromAlpha="0.0" 
     android:interpolator="@android:anim/accelerate_interpolator" 
     android:toAlpha="1.0" /> 

</set> 

И в CreateView

ListView lv = getListView(); 

AnimationSet set = new AnimationSet(true); 
Animation animation = AnimationUtils.loadAnimation(getContext(), 
      R.anim.fadein); 
set.addAnimation(animation); 
LayoutAnimationController controller = new LayoutAnimationController(
     set, 0.5f); 
lv.setLayoutAnimation(controller); 

И удалить AnimationAdapterCode

+0

Я редактировал коды. Пожалуйста, проверьте это. – AimanB

+0

Оформить заказ мой отредактированный ан. –

1

Я думаю, что вы должны исправить onPostExecute(). Это работает на основном или потоке пользовательского интерфейса. Вам не нужен runOnUiThread() внутри onPostExecute().

Теперь, когда мы используем библиотечную часть: вы добавите файл jar в свой проект под папкой libs и убедитесь, что он также связан, когда вы создаете apk. Шаги по добавлению библиотеки зависят от того, какую IDE вы используете - Eclipse или Android-Studio.

Если файл jar не доступен сразу, вам может потребоваться построить его сначала из имеющейся у вас ссылки github.

Наконец, на githib есть папка examples. Это должно сказать вам, как использовать библиотеку ListViewAnimations.

HTH.

+0

Импортировал все библиотеки. Я также следил за папкой с примерами, пытался отключить все, что я не хочу (например, панель действий). Я думаю, мой немного сложнее для использования AsyncTask для извлечения данных с сервера и заполнения его в listview? – AimanB

+0

Итак, вы можете видеть данные в удобном пользовательском списке. Что не работает, это просто часть анимации? –

+0

Я редактировал коды. Пожалуйста, проверьте это. – AimanB

2

Вы сделали это -

Adapter adapter = new Adapter(this, 1, notificationList); 
     AnimationAdapter animAdapter = new AlphaInAnimationAdapter(adapter); 
     animAdapter.setAbsListView(listView); 
     listView.setAdapter(animAdapter); 
+0

Я редактировал коды. Пожалуйста, проверьте это. – AimanB

1

Проблема заключается в том, что ваш адаптер изменяется следующим образом и заставляет меня знать, что он работает или нет.

import java.util.ArrayList; 
import java.util.HashMap; 

import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.TextView; 

public class CategoryListAdapter extends ArrayAdapter<HashMap<String, String>> 
{ 
    private Context mContext; 
    LayoutInflater inflater; 
    private final ArrayList<HashMap<String, String>> urls; 


    public CategoryListAdapter(Context context,int res, ArrayList<HashMap<String, String>> items) { 
     super(context, res); 
     this.mContext = context; 
     urls = items; 
    } 

    @Override 
    public int getCount() 
    { 
     return urls.size(); 
    } 
    @Override 
    public long getItemId(int position) 
    { 
     return position; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) 
    {HashMap<String, String> resultp = new HashMap<String, String>(); 
     ViewHolder holder = null; 
     if (convertView == null) 
     { 
      LayoutInflater mInflater = (LayoutInflater) mContext 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      convertView = mInflater.inflate(R.layout.list_row1, null); 
      holder = new ViewHolder(); 
      holder.item_name = (TextView) convertView.findViewById(R.id.category_name); 
      holder.item_count = (TextView) convertView.findViewById(R.id.songs_count); 
      holder.item_id = (TextView) convertView.findViewById(R.id.category_id);  
      convertView.setTag(holder); 

     } 
     else holder = (ViewHolder) convertView.getTag(); 
     resultp = urls.get(position); 
     holder.item_name.setText(resultp.get(CategoryActivity.TAG_NAME)); 
     holder.item_count.setText(resultp.get(CategoryActivity.TAG_CATEGORIES_COUNT)); 
     holder.item_id.setText(resultp.get(CategoryActivity.TAG_ID)); 

     return convertView; 
    } 

    static class ViewHolder 
    { 
     TextView item_name; 
     TextView item_count; 
     TextView item_id; 
    } 
} 
Смежные вопросы