Android Open Source - DualReader-Android Dual Reader Activity






From Project

Back to project page DualReader-Android.

License

The source code is released under:

Apache License

If you think the Android project DualReader-Android listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.diego4aim.dualreader;
//  w  w  w  .j ava2s . c  o  m
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.diego4aim.dualreader.AsyncPageRetriever.OnRetrievalListener;
import com.diego4aim.dualreader.util.BackgroundSelector;

/**
 * Main activity of the application. Its layout contains two buttons and a
 * reading pane. As the buttons are clicked, the reading pane gets a reading.
 * <p/>
 * The reading pane is optimized for huge texts, as only a buffer of a few lines
 * is maintained in memory. When the user clicks any line on the top 5, the
 * previous page is loaded. Likewise, when any of the last 5 lines is clicked,
 * the next page is loaded.
 */
public class DualReaderActivity extends Activity implements OnRetrievalListener {

    private ListView mListView = null;
    private ArrayAdapter<String> mAdapter = null;

    // An AsyncPageRetriever is a fa?ade that brings pages to the reading pane
    // cache without blocking the UI thread.
    private AsyncPageRetriever mRetriever = null;

    // A BackgroundSelector is a helper class that selects different background
    // colors as the buttons are clicked.
    private BackgroundSelector mBackgroundSelector = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reader);

        mBackgroundSelector = BackgroundSelector.createInstance();

        setupButtons();
        setupListView();
    }

    // Both buttons, when clicked, will change their background colors, loading
    // each the reading panel with a content of theirs.
    private void setupButtons() {
        final Button button1 = (Button) findViewById(R.id.button_1);
        final Button button2 = (Button) findViewById(R.id.button_2);

        // this event listener reacts to the click of any button, changing their
        // background colors and loading a reading to the list view.
        View.OnClickListener buttonsClickListener = new View.OnClickListener() {

            // the last button clicked is kept, because if the same button is
            // pressed twice, there's no need to reset a reading that is already
            // being read.
            private int mPreviousClickedButton = 0;

            @Override
            public void onClick(View v) {
                // By design, the only components that this listener reacts to
                // are the buttons "1" and "2"
                if ((button1.equals(v)) || (button2.equals(v))) {
                    // And the reaction is a change in the background color
                    changeBackgroundColor();

                    int clickedButton = getButtonLabelAsInt((Button) v);
                    // If the button clicked isn't the same clicked the last
                    // time...
                    if (mPreviousClickedButton != clickedButton) {
                        // ... then the reading pane is reloaded with the
                        // reading associated to that button.
                        loadList(clickedButton);
                        mPreviousClickedButton = clickedButton;
                    }
                }
            }

            // Sets the next available background color to the buttons.
            private void changeBackgroundColor() {
                int backgroundResourceId = mBackgroundSelector
                        .getNextBackground();

                button1.setBackgroundResource(backgroundResourceId);
                button2.setBackgroundResource(backgroundResourceId);
            }

        };

        // Now, let's assign it to the buttons
        button1.setOnClickListener(buttonsClickListener);
        button2.setOnClickListener(buttonsClickListener);
    }

    private int getButtonLabelAsInt(Button button) {
        return Integer.parseInt((button).getText().toString());
    }

    // populates the list cache with the first "page" of strings associated
    // to the button
    private void loadList(int button) {
        // the page retriever is asynchronous, to avoid a long-running task in
        // the UI thread.
        mRetriever.requestBookFirstPage(button);
    }

    // (By design, the list view ListAdapter is to be an ArrayAdapter. Then
    // warnings for unchecked casts are suppressed.)
    @SuppressWarnings("unchecked")
    // This method sets up the event listener that the list view requires to
    // turn the page forward or backward.
    private void setupListView() {
        mListView = (ListView) findViewById(R.id.reading_box);

        if (mAdapter == null) {
            mAdapter = (ArrayAdapter<String>) createListAdapter();
        }
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                if (position < 5) {
                    mRetriever.requestPreviousPage();
                } else if (position >= 20) {
                    mRetriever.requestNextPage();
                }
            }

        });

        // finally, the PageRetriever is initialized
        if (mRetriever == null) {
            mRetriever = new AsyncPageRetriever(this);
        }
    }

    // Implements the creation of the container in which the list view is
    // backed on. This convenience method encapsulates the detail that the
    // adapter is an ArrayAdapter
    private ListAdapter createListAdapter() {
        return new ArrayAdapter<String>(this, R.layout.list_item,
                new ArrayList<String>());
    }

    /**
     * This callback method is invoked by the {@link AsyncPageRetriever}, so the
     * just retrieved page is cached into the reading pane buffer.
     */
    @Override
    public void onPageRetrieved(List<String> page) {
        if (mAdapter != null) {
            mAdapter.clear();
            // to support Gingerbread (API 10), mAdapter.addAll(page) can't be
            // used. Instead, we have to proceed iteratively
            for (String line : page) {
                mAdapter.add(line);
            }

            mAdapter.notifyDataSetChanged();
            // Every time a new page is retrieved, the reading pane must be
            // reset to the first line, so the user don't need to scroll there
            // to keep reading. As onPageRetrieved is being invoked by an
            // asynchronous method without access to the UI, this scroll to the
            // top has to be queued in the UI thread -i.e., View.post(Runnable).
            mListView.post(new Runnable() {

                @Override
                public void run() {
                    mListView.smoothScrollToPosition(0);
                }
            });
        }
    }

    // Auto generated
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.reader, menu);
        return true;
    }

    // Auto generated
    @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);
    }
}




Java Source Code List

com.diego4aim.dualreader.AsyncPageRetriever.java
com.diego4aim.dualreader.DualReaderActivity.java
com.diego4aim.dualreader.PageRetrievalStrategy.java
com.diego4aim.dualreader.util.BackgroundSelector.java
com.diego4aim.dualreader.util.GlobalContextApplication.java