Skip to main content

Supporting Multiple Screens

Supporting Multiple Screens

public class ArticleActivity extends FragmentActivity {
    // The news category index and the article index for the article we are to display
    int mCatIndex, mArtIndex;

    /**
     * Sets up the activity.
     *
     * Setting up the activity means reading the category/article index from the Intent that
     * fired this Activity and loading it onto the UI. We also detect if there has been a
     * screen configuration change (in particular, a rotation) that makes this activity
     * unnecessary, in which case we do the honorable thing and get out of the way.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCatIndex = getIntent().getExtras().getInt("catIndex", 0);
        mArtIndex = getIntent().getExtras().getInt("artIndex", 0);

        // If we are in two-pane layout mode, this activity is no longer necessary
        if (getResources().getBoolean(R.bool.has_two_panes)) {
            finish();
            return;
        }

        // Place an ArticleFragment as our content pane
        ArticleFragment f = new ArticleFragment();
        getSupportFragmentManager().beginTransaction().add(android.R.id.content, f).commit();

        // Display the correct news article on the fragment
        NewsArticle article = NewsSource.getInstance().getCategory(mCatIndex).getArticle(mArtIndex);
        f.displayArticle(article);
    }
}

---------------------------------------------------------------------------------------

/**
 * Fragment that displays a news article.
 */
public class ArticleFragment extends Fragment {
    // The webview where we display the article (our only view)
    WebView mWebView;

    // The article we are to display
    NewsArticle mNewsArticle = null;

    // Parameterless constructor is needed by framework
    public ArticleFragment() {
        super();
    }

    /**
     * Sets up the UI. It consists if a single WebView.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mWebView = new WebView(getActivity());
        loadWebView();
        return mWebView;
    }

    /**
     * Displays a particular article.
     *
     * @param article the article to display
     */
    public void displayArticle(NewsArticle article) {
        mNewsArticle = article;
        loadWebView();
    }

    /**
     * Loads article data into the webview.
     *
     * This method is called internally to update the webview's contents to the appropriate
     * article's text.
     */
    void loadWebView() {
        if (mWebView != null) {
            mWebView.loadData(mNewsArticle == null ? "" : mNewsArticle.getBody(), "text/html",
                        "utf-8");
        }
    }
}

-------------------------------------------------------------------------------------

public class CompatActionBarNavHandler implements TabListener,
        OnNavigationListener {
    // The listener that we notify of navigation events
    CompatActionBarNavListener mNavListener;

    /**
     * Constructs an instance with the given listener.
     *
     * @param listener
     *            the listener to notify when a navigation event occurs.
     */
    public CompatActionBarNavHandler(CompatActionBarNavListener listener) {
        mNavListener = listener;
    }

    /**
     * Called by framework when a tab is selected.
     *
     * This will cause a navigation event to be delivered to the configured
     * listener.
     */
    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
        mNavListener.onCategorySelected(tab.getPosition());
    }

    /**
     * Called by framework when a item on the navigation menu is selected.
     *
     * This will cause a navigation event to be delivered to the configured
     * listener.
     */
    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        mNavListener.onCategorySelected(itemPosition);
        return true;
    }

    /**
     * Called by framework when a tab is re-selected. That is, it was already
     * selected and is tapped on again. This is not used in our app.
     */
    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // we don't care
    }

    /**
     * Called by framework when a tab is unselected. Not used in our app.
     */
    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // we don't care
    }

}
----------------------------------------------------------------------------------

public interface CompatActionBarNavListener {
    /**
     * Signals that the given news category was selected.
     * @param catIndex the selected category's index.
     */
    public void onCategorySelected(int catIndex);
}

------------------------------------------------------------------------------------

public class HeadlinesFragment extends ListFragment implements OnItemClickListener {
    // The list of headlines that we are displaying
    List<String> mHeadlinesList = new ArrayList<String>();

    // The list adapter for the list we are displaying
    ArrayAdapter<String> mListAdapter;

    // The listener we are to notify when a headline is selected
    OnHeadlineSelectedListener mHeadlineSelectedListener = null;

    /**
     * Represents a listener that will be notified of headline selections.
     */
    public interface OnHeadlineSelectedListener {
        /**
         * Called when a given headline is selected.
         * @param index the index of the selected headline.
         */
        public void onHeadlineSelected(int index);
    }

    /**
     * Default constructor required by framework.
     */
    public HeadlinesFragment() {
        super();
    }

    @Override
    public void onStart() {
        super.onStart();
        setListAdapter(mListAdapter);
        getListView().setOnItemClickListener(this);
        loadCategory(0);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mListAdapter = new ArrayAdapter<String>(getActivity(), R.layout.headline_item,
                mHeadlinesList);
    }

    /**
     * Sets the listener that should be notified of headline selection events.
     * @param listener the listener to notify.
     */
    public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener listener) {
        mHeadlineSelectedListener = listener;
    }

    /**
     * Load and display the headlines for the given news category.
     * @param categoryIndex the index of the news category to display.
     */
    public void loadCategory(int categoryIndex) {
        mHeadlinesList.clear();
        int i;
        NewsCategory cat = NewsSource.getInstance().getCategory(categoryIndex);
        for (i = 0; i < cat.getArticleCount(); i++) {
            mHeadlinesList.add(cat.getArticle(i).getHeadline());
        }
        mListAdapter.notifyDataSetChanged();
    }

    /**
     * Handles a click on a headline.
     *
     * This causes the configured listener to be notified that a headline was selected.
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (null != mHeadlineSelectedListener) {
            mHeadlineSelectedListener.onHeadlineSelected(position);
        }
    }

    /** Sets choice mode for the list
     *
     * @param selectable whether list is to be selectable.
     */
    public void setSelectable(boolean selectable) {
        if (selectable) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
        else {
            getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
        }
    }
}
---------------------------------------------------------------------------------

public class NewsArticle {
    // How many sentences in each paragraph?
    final int SENTENCES_PER_PARAGRAPH = 20;

    // How many paragraphs in each article?
    final int PARAGRAPHS_PER_ARTICLE = 5;

    // Headline and body
    String mHeadline, mBody;

    /**
     * Create a news article with randomly generated text.
     * @param ngen the nonsense generator to use.
     */
    public NewsArticle(NonsenseGenerator ngen) {
        mHeadline = ngen.makeHeadline();

        StringBuilder sb = new StringBuilder();
        sb.append("<html><body>");
        sb.append("<h1>" + mHeadline + "</h1>");
        int i;
        for (i = 0; i < PARAGRAPHS_PER_ARTICLE; i++) {
            sb.append("<p>").append(ngen.makeText(SENTENCES_PER_PARAGRAPH)).append("</p>");
        }

        sb.append("</body></html>");
        mBody = sb.toString();
    }

    /** Returns the headline. */
    public String getHeadline() {
        return mHeadline;
    }

    /** Returns the article body (HTML)*/
    public String getBody() {
        return mBody;
    }
}
------------------------------------------------------------------------------

public class NewsCategory {
    // how many articles?
    final int ARTICLES_PER_CATEGORY = 20;

    // array of our articles
    NewsArticle[] mArticles;

    /**
     * Create a news category.
     *
     * The articles are dynamically generated with fun and random nonsense.
     */
    public NewsCategory() {
        NonsenseGenerator ngen = new NonsenseGenerator();
        mArticles = new NewsArticle[ARTICLES_PER_CATEGORY];
        int i;
        for (i = 0; i < mArticles.length; i++) {
            mArticles[i] = new NewsArticle(ngen);
        }
    }

    /** Returns how many articles exist in this category. */
    public int getArticleCount() {
        return mArticles.length;
    }

    /** Gets a particular article by index. */
    public NewsArticle getArticle(int index) {
        return mArticles[index];
    }
}

Comments

Popular posts from this blog

Bitmap scalling and cropping from center

How to Bitmap scalling and cropping from center? public class ScalingUtilities {     /**      * Utility function for decoding an image resource. The decoded bitmap will      * be optimized for further scaling to the requested destination dimensions      * and scaling logic.      *      * @param res      *            The resources object containing the image data      * @param resId      *            The resource id of the image data      * @param dstWidth      *            Width of destination area      * @param dstHeight      *     ...

Custom camera using SurfaceView android with autofocus & auto lights & more

Custom camera using SurfaceView android with autofocus & auto lights & much more /**  * @author Tatyabhau Chavan  *  */ public class Preview extends SurfaceView implements SurfaceHolder.Callback {     private SurfaceHolder mHolder;     private Camera mCamera;     public Camera.Parameters mParameters;     private byte[] mBuffer;     private Activity mActivity;     // this constructor used when requested as an XML resource     public Preview(Context context, AttributeSet attrs) {         super(context, attrs);         init();     }     public Preview(Context context) {         super(context);         init();     }     public Camera getCamera() {        ...

Recycle view adapter in android

Recycle view adapter             The   RecyclerView   widget is a more advanced and flexible version of   ListView . This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Use the   RecyclerView widget when you have data collections whose elements change at runtime based on user action or network events. The   RecyclerView   class simplifies the display and handling of large data sets by providing: ·          Layout managers for positioning items ·          Default animations for common item operations, such as removal or addition of items You also have the flexibility to define custom layout managers and animations for   RecyclerView   widgets. RecyclerViewFragment.class public class RecyclerViewFragment...