Monday, May 6, 2013

Android Pinterest Listview Example

Android Pinterest Listview Example

This post about Pinterest Listview in Android.
What is Pinterest Listview?
Display the items in multiple columns using multiple Listview on single screen.
Below i added the code for pinterest view.

Check Out This LINK  : Click here
Displaying data from two different rss feed using two listview in single screen



Activity Source Code
package com.androidbunch.pinterest.listview;

import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;


/**
 *
 * @author VIJAYAKUMAR M
 *
 */
public class MainActivity extends Activity  {
     
      private ListView listViewLeft;
      private ListView listViewRight;
      private RssReaderListAdapter leftAdapter;
      private RssReaderListAdapter rightAdapter;

      int[] leftViewsHeights;
      int[] rightViewsHeights;
      List<RssFeedStructure> rssStr ;
      List<RssFeedStructure> tam ;
      private RssReaderListAdapter _adapter;
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.items_list);     
           
            listViewLeft = (ListView) findViewById(R.id.list_view_left);
            listViewRight = (ListView) findViewById(R.id.list_view_right);
            RssFeedTask rss = new RssFeedTask();
            rss.execute();
            listViewLeft.setOnTouchListener(touchListener);
            listViewRight.setOnTouchListener(touchListener);           
            listViewLeft.setOnScrollListener(scrollListener);
            listViewRight.setOnScrollListener(scrollListener);
      }
     
      // Passing the touch event to the opposite list
      OnTouchListener touchListener = new OnTouchListener() {                            
            boolean dispatched = false;
           
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                  if (v.equals(listViewLeft) && !dispatched) {
                        dispatched = true;
                        listViewRight.dispatchTouchEvent(event);
                  } else if (v.equals(listViewRight) && !dispatched) {
                        dispatched = true;
                        listViewLeft.dispatchTouchEvent(event);
                  }
                 
                  dispatched = false;
                  return false;
            }
      };
     
      /**
       * Synchronizing scrolling
       * Distance from the top of the first visible element opposite list:
       * sum_heights(opposite invisible screens) - sum_heights(invisible screens) + distance from top of the first visible child
       */
      OnScrollListener scrollListener = new OnScrollListener() {
           
            @Override
            public void onScrollStateChanged(AbsListView v, int scrollState) {     
            }
           
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                        int visibleItemCount, int totalItemCount) {
                 
                  if (view.getChildAt(0) != null) {
                        if (view.equals(listViewLeft) ){
                              leftViewsHeights[view.getFirstVisiblePosition()] = view.getChildAt(0).getHeight();
                             
                              int h = 0;
                              for (int i = 0; i < listViewRight.getFirstVisiblePosition(); i++) {
                                    h += rightViewsHeights[i];
                              }
                             
                              int hi = 0;
                              for (int i = 0; i < listViewLeft.getFirstVisiblePosition(); i++) {
                                    hi += leftViewsHeights[i];
                              }
                             
                              int top = h - hi + view.getChildAt(0).getTop();
                              listViewRight.setSelectionFromTop(listViewRight.getFirstVisiblePosition(), top);
                        } else if (view.equals(listViewRight)) {
                              rightViewsHeights[view.getFirstVisiblePosition()] = view.getChildAt(0).getHeight();
                             
                              int h = 0;
                              for (int i = 0; i < listViewLeft.getFirstVisiblePosition(); i++) {
                                    h += leftViewsHeights[i];
                              }
                             
                              int hi = 0;
                              for (int i = 0; i < listViewRight.getFirstVisiblePosition(); i++) {
                                    hi += rightViewsHeights[i];
                              }
                             
                              int top = h - hi + view.getChildAt(0).getTop();
                              listViewLeft.setSelectionFromTop(listViewLeft.getFirstVisiblePosition(), top);
                        }
                       
                  }
                 
            }
      };
     
       private class RssFeedTask extends AsyncTask<String, Void, String> {
                  // private String Content;
                  private ProgressDialog Dialog;
                  String response = "";

                  @Override
                  protected void onPreExecute() {
                        Dialog = new ProgressDialog(MainActivity.this);
                        Dialog.setMessage("Rss Loading...");
                       Dialog.show();
                  }
                  @Override
                  protected String doInBackground(String... urls) {
                          try {
                             
                                String feed = "http://timesofindia.feedsportal.com/c/33039/f/533965/index.rss";
                                String tamil = "http://www.dinakaran.com/rss_Latest.asp";
                                XmlHandler rh = new XmlHandler();
                                XmlHandler rh1 = new XmlHandler();
                                rssStr = rh.getLatestArticles(feed);
                                tam = rh1.getLatestArticles(tamil);
                                response = "in";
                                } catch (Exception e) {
                              response = "out";
                                }
                        return response;
                  }

                  @Override
                  protected void onPostExecute(String result) {
                            leftAdapter = new RssReaderListAdapter(MainActivity.this,rssStr);
                              rightAdapter =new RssReaderListAdapter(MainActivity.this,tam);
                              listViewLeft.setAdapter(leftAdapter);
                              listViewRight.setAdapter(rightAdapter);
                              leftViewsHeights = new int[rssStr.size()];
                              rightViewsHeights = new int[tam.size()]; 
                          Dialog.dismiss();
                  }
            }

}

Adapter Source Code




package com.androidbunch.pinterest.listview;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import android.app.Activity;
import android.text.SpannableString;
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.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 *
 * @author VIJAYAKUMAR M
 *
 */

public class RssReaderListAdapter extends ArrayAdapter<RssFeedStructure> {
      List<RssFeedStructure> imageAndTexts1 =null;
       public ImageLoader imageLoader;
      // float imageWidth;
       Activity act;
public RssReaderListAdapter(Activity activity, List<RssFeedStructure> imageAndTexts) {
super(activity, 0, imageAndTexts);
imageAndTexts1 = imageAndTexts;
act = activity;
imageLoader=new ImageLoader(activity.getApplicationContext());

}


@Override
public View getView(final int position, View convertView, ViewGroup parent) {

Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();


View rowView = inflater.inflate(R.layout.rssfeedadapter_layout, null);
TextView textView = (TextView) rowView.findViewById(R.id.feed_text);
TextView timeFeedText = (TextView) rowView.findViewById(R.id.feed_updatetime);
Button btn = (Button) rowView.findViewById(R.id.button1);

btn.setOnClickListener(new OnClickListener() {
     
      @Override
      public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(act, imageAndTexts1.get(position).getTitle(), Toast.LENGTH_LONG).show();
      }
});
ImageView imageView = (ImageView) rowView.findViewById(R.id.feed_image);
        try {
           
            Log.d("rssfeed", "imageAndTexts1.get(position).getImgLink() :: " +imageAndTexts1.get(position).getImgLink() +" :: " +imageAndTexts1.get(position).getTitle());
            textView.setText(imageAndTexts1.get(position).getTitle());
            SpannableString content = new SpannableString(imageAndTexts1.get(position).getPubDate());
            timeFeedText.setText(content);
            if(imageAndTexts1.get(position).getImgLink() !=null){
            URL feedImage= new URL(imageAndTexts1.get(position).getImgLink().toString());
            if(!feedImage.toString().equalsIgnoreCase("null")){
                  
            }
             else{
                
             }
                  }
      
           
        } catch (MalformedURLException e) {
      
        }
        catch (IOException e) {
       
        }

return rowView;

}


}
 


XmlHandler Source Code




package com.androidbunch.pinterest.listview;


import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;


public class XmlHandler extends DefaultHandler {
private RssFeedStructure feedStr = new RssFeedStructure();
private List<RssFeedStructure> rssList = new ArrayList<RssFeedStructure>();

private int articlesAdded = 0;

// Number of articles to download
private static final int ARTICLES_LIMIT = 50;

StringBuffer chars = new StringBuffer();

public void startElement(String uri, String localName, String qName, Attributes atts) {
chars = new StringBuffer();

 if (qName.equalsIgnoreCase("enclosure"))
     
{
       if(!atts.getValue("url").toString().equalsIgnoreCase("null")){
       feedStr.setImgLink(atts.getValue("url").toString());
       }
       else{
             feedStr.setImgLink("");
       }
}

}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("title"))
{
      feedStr.setTitle(chars.toString());
}
else if (localName.equalsIgnoreCase("description"))
{

      feedStr.setDescription(chars.toString());
}
else if (localName.equalsIgnoreCase("pubDate"))
{

      feedStr.setPubDate(chars.toString());
}
else if (localName.equalsIgnoreCase("encoded"))
{

      feedStr.setEncodedContent(chars.toString());
}
else if (qName.equalsIgnoreCase("media:content"))
     
{
     
}
else if (localName.equalsIgnoreCase("link"))
{
      feedStr.setUrl(chars.toString());

}
if (localName.equalsIgnoreCase("item")) {
rssList.add(feedStr);

feedStr = new RssFeedStructure();
articlesAdded++;
if (articlesAdded >= ARTICLES_LIMIT)
{
throw new SAXException();
}
}
}

public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}


public List<RssFeedStructure> getLatestArticles(String feedUrl) {
URL url = null;
try {

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
url = new URL(feedUrl);
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
} catch (SAXException e) {

} catch (ParserConfigurationException e) {

}

return rssList;
}

}
  

items_list.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"
    android:background="#FFFFFF"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >


<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:background="#FFFFFF"
  
  >
    <ListView
        android:id="@+id/list_view_left"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:paddingRight="5dp"
        android:scrollbars="none" >
    </ListView>
<View android:layout_height="fill_parent" android:layout_width="1dip" android:background="#E4E4E4" />
    <ListView
        android:id="@+id/list_view_right"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:paddingLeft="5dp"
        android:scrollbars="none" >
    </ListView>
</LinearLayout>
</LinearLayout>
  

rssfeedadapter_layout.xml

 


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:padding="2dip" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dip" >

        <ImageView
            android:id="@+id/feed_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
          
            android:paddingRight="3dip"
            android:paddingTop="15dip" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </LinearLayout>
    </LinearLayout>

    <TextView
        android:id="@+id/feed_updatetime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/feed_text"
        android:layout_below="@+id/linearLayout1"
        android:paddingBottom="3dip"
        android:paddingLeft="8dip"
        android:paddingRight="8dip"
        android:paddingTop="3dip"
        android:text="afsdfd"
        android:textColor="#A4A4A4"
        android:textSize="8dip" />

    <TextView
        android:id="@+id/feed_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/linearLayout1"
        android:layout_below="@+id/feed_updatetime"
        android:maxLines="5"
        android:paddingBottom="15dip"
        android:paddingLeft="8dip"
        android:paddingRight="8dip"
        android:text="afsdfd"
        android:textColor="#000000" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/feed_text"
        android:text="Full News" />

</RelativeLayout>






Check out this may be help you

Related Posts Plugin for WordPress, Blogger...