Sunday, February 19, 2017

Implement transparent status bar for android.support.v7.widget.Toolbar

Implement transparent status bar for android.support.v7.widget.Toolbar:

- Follow the steps in "Replace ActionBar with android.support.v7.widget.Toolbar" to implement a simplest toolbar.


- Edit styles.xml to add the item of "android:windowTranslucentStatus".
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowTranslucentStatus">true</item>
    </style>

</resources>


Edit MainActivity.java to set the padding (with the height of status bar) of the status.
package com.blogspot.android_er.androidtoolbarex2;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        toolbar.setPadding(0, getStatusBarHeight(), 0, 0);

    }

    private int getStatusBarHeight() {
        int height;

        Resources myResources = getResources();
        int idStatusBarHeight = myResources.getIdentifier(
                "status_bar_height", "dimen", "android");
        if (idStatusBarHeight > 0) {
            height = getResources().getDimensionPixelSize(idStatusBarHeight);
            Toast.makeText(this,
                    "Status Bar Height = " + height,
                    Toast.LENGTH_LONG).show();
        }else{
            height = 0;
            Toast.makeText(this,
                    "Resources NOT found",
                    Toast.LENGTH_LONG).show();
        }

        return height;
    }
}


After finished:




Monday, February 13, 2017

Get the height of status bar

Example to get the height of status bar, in size of pixel.



package com.blogspot.android_er.androidgetstatusbarheight;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        getStatusBarHeight();
    }

    private int getStatusBarHeight() {
        int height;

        Resources myResources = getResources();
        int idStatusBarHeight = myResources.getIdentifier(
                "status_bar_height", "dimen", "android");
        if (idStatusBarHeight > 0) {
            height = getResources().getDimensionPixelSize(idStatusBarHeight);
            Toast.makeText(this,
                    "Status Bar Height = " + height,
                    Toast.LENGTH_LONG).show();
        }else{
            height = 0;
            Toast.makeText(this,
                    "Resources NOT found",
                    Toast.LENGTH_LONG).show();
        }

        return height;
    }
}


Remix OS is Android PC. Re-imagining mobile. Redefining PC.

Remix OS for PC, now powered by Android Marshmallow,  allows you to run PC optimized version of Android on any computer. Through a simple and quick setup process, enjoy millions of Android apps and games on your PC alongside the many intuitive and amazing PC features we’ve engineered into Remix OS.

Learn more: http://www.jide.com/remixos-for-pc


Saturday, February 11, 2017

Building interfaces with ConstraintLayout in Android Studio

The new Layout Editor in Android Studio 2.2 include a new blueprint mode, revamped properties inspector and support for ConstraintLayout, a new way to define layouts for your apps.


In this Android Tool Time episode Wojtek Kaliciński shows you the basics of working with ConstraintLayouts in the visual editor. If you want to try it out yourself, you can find our codelab here: https://codelabs.developers.google.com/codelabs/constraint-layout

When you’re familiar with the layout editor interface, read the rest of our Medium article where you’ll find some more advanced tips and tricks for ConstraintLayout: https://goo.gl/a5orYw


Monday, February 6, 2017

IOException: not create document. Error

When I prepare the example "Display PDF in assets folder (inside APK)", I face with the error of "java.io.IOException: not create document. Error". It should be generated by the code:

pdfRenderer = new PdfRenderer(fileDescriptor);


Somebody commented it's caused by new version of Gradle (ref: https://github.com/googlesamples/android-PdfRendererBasic/issues/1), so I edit dependencies of buildscript in build.gradle (Project: ...), use gradle:2.1.2 to solve this problem.


Display PDF in assets folder (inside APK)

The example "Display PDF using PdfRenderer" show how to display PDF stored in sdcard, this example show how to display PDF stored in assets inside APK.


First, you have to create assets folder and copy your PDF into it.


Then you have to edit aaptOptions in build.gradle (Module: app), not to compass "pdf" file.


    aaptOptions {
        noCompress "pdf"
    }

Layout file, refer to the example "Create PDF using PdfDocument".

MainActivity.java
package com.blogspot.android_er.androidpdf;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.pdf.PdfRenderer;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    ImageView pdfView;

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

        pdfView = (ImageView)findViewById(R.id.pdfview);

        try {
            openPDF();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this,
                    "Something Wrong: " + e.toString(),
                    Toast.LENGTH_LONG).show();
        }
    }

    private void openPDF() throws IOException {

        //open file in assets

        AssetManager assetManager = getAssets();
        AssetFileDescriptor assetFileDescriptor = 
                assetManager.openFd("test.pdf");
        ParcelFileDescriptor fileDescriptor = 
                assetFileDescriptor.getParcelFileDescriptor();

        //open file from sdcard
        /*
        String targetPdf = "/sdcard/test.pdf";
        File file = new File(targetPdf);

        ParcelFileDescriptor fileDescriptor = null;
        fileDescriptor = ParcelFileDescriptor.open(
                file, ParcelFileDescriptor.MODE_READ_ONLY);
        */

        //min. API Level 21
        PdfRenderer pdfRenderer = null;
        pdfRenderer = new PdfRenderer(fileDescriptor);

        final int pageCount = pdfRenderer.getPageCount();
        Toast.makeText(this,
                "pageCount = " + pageCount,
                Toast.LENGTH_LONG).show();

        //Display page 0
        PdfRenderer.Page rendererPage = pdfRenderer.openPage(1);
        int rendererPageWidth = rendererPage.getWidth();
        int rendererPageHeight = rendererPage.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(
                rendererPageWidth,
                rendererPageHeight,
                Bitmap.Config.ARGB_8888);
        rendererPage.render(bitmap, null, null,
                PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);

        pdfView.setImageBitmap(bitmap);
        rendererPage.close();

        pdfRenderer.close();

        assetFileDescriptor.close();
    }
}




Remark: If you reported with the error "java.io.IOException: not create document. Error:", read next post.

Create assets folder in Android Studio, and copy file into.

How to create assets folder in Android Studio, and copy a PDF file into the assets folder.

Sunday, February 5, 2017

Create PDF using PdfDocument


android.graphics.pdf.PdfDocument enables generating a PDF document from native Android content. This example show how to create a two page PDF file using PdfDocument, store as "/sdcard/test.pdf". Then use last example Display PDF using PdfRenderer to view it.

(remark: if you use last example to view the PDF file, you have to change targetPdf = "/sdcard/test.pdf".)


MainActivity.java
package com.blogspot.android_er.androidcreatepdf;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    Button btnCreate;

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

        btnCreate = (Button)findViewById(R.id.create);
        btnCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createPdf();
            }
        });

    }

    private void createPdf(){
        // create a new document
        PdfDocument document = new PdfDocument();

        // crate a page description
        PdfDocument.PageInfo pageInfo = 
                new PdfDocument.PageInfo.Builder(100, 100, 1).create();

        // start a page
        PdfDocument.Page page = document.startPage(pageInfo);

        Canvas canvas = page.getCanvas();

        Paint paint = new Paint();
        paint.setColor(Color.RED);

        canvas.drawCircle(50, 50, 30, paint);

        // finish the page
        document.finishPage(page);

        // Create Page 2
        pageInfo = new PdfDocument.PageInfo.Builder(500, 500, 2).create();
        page = document.startPage(pageInfo);
        canvas = page.getCanvas();
        paint = new Paint();
        paint.setColor(Color.BLUE);
        canvas.drawCircle(200, 200, 100, paint);
        document.finishPage(page);

        // write the document content
        String targetPdf = "/sdcard/test.pdf";
        File filePath = new File(targetPdf);
        try {
            document.writeTo(new FileOutputStream(filePath));
            Toast.makeText(this, "Done", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Something wrong: " + e.toString(),
                    Toast.LENGTH_LONG).show();
        }

        // close the document
        document.close();
    }
}


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:orientation="vertical"
    tools:context="com.blogspot.android_er.androidcreatepdf.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold"/>

    <Button
        android:id="@+id/create"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Create PDF"/>
</LinearLayout>



uses-permission of "android.permission.WRITE_EXTERNAL_STORAGE" is needed in AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.blogspot.android_er.androidcreatepdf">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

</manifest>

Saturday, February 4, 2017

Display PDF using PdfRenderer


The class android.graphics.pdf.PdfRenderer enables rendering a PDF document. This example show how to:


MainActivity.java
package com.blogspot.android_er.androidpdf;

import android.graphics.Bitmap;
import android.graphics.pdf.PdfRenderer;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    String targetPdf = "/sdcard/MagPi54.pdf";

    ImageView pdfView;

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

        pdfView = (ImageView)findViewById(R.id.pdfview);

        try {
            openPDF();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this,
                    "Something Wrong: " + e.toString(),
                    Toast.LENGTH_LONG).show();
        }
    }

    private void openPDF() throws IOException {
        File file = new File(targetPdf);

        ParcelFileDescriptor fileDescriptor = null;
        fileDescriptor = ParcelFileDescriptor.open(
                file, ParcelFileDescriptor.MODE_READ_ONLY);

        //min. API Level 21
        PdfRenderer pdfRenderer = null;
        pdfRenderer = new PdfRenderer(fileDescriptor);

        final int pageCount = pdfRenderer.getPageCount();
        Toast.makeText(this,
                "pageCount = " + pageCount,
                Toast.LENGTH_LONG).show();

        //Display page 0
        PdfRenderer.Page rendererPage = pdfRenderer.openPage(0);
        int rendererPageWidth = rendererPage.getWidth();
        int rendererPageHeight = rendererPage.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(
                rendererPageWidth,
                rendererPageHeight,
                Bitmap.Config.ARGB_8888);
        rendererPage.render(bitmap, null, null,
                PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);

        pdfView.setImageBitmap(bitmap);
        rendererPage.close();

        pdfRenderer.close();
        fileDescriptor.close();
    }
}


layout/activity_main.xml, add a ImageView to display the PDF:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.blogspot.android_er.androidpdf.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold"/>

    <ImageView
        android:id="@+id/pdfview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>


uses-permission of "android.permission.READ_EXTERNAL_STORAGE" is needed in AndroidManifest.xml to read file from sdcard.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.blogspot.android_er.androidpdf">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

</manifest>

Next:
Display PDF in assets folder (inside APK)

Related:
Create PDF using PdfDocument

Change minSdkVersion, targetSdkVersion, compileSdkVersion in Android Studio



To change minSdkVersion in Android Studio:

- Right click your app -> Open Module Settings

- Select app and Flavors tab, select your new Min Sdk Version, then OK.

- minSdkVersion changed.

You can also change targetSdkVersion, compileSdkVersion (under Properties tab) also.

Friday, February 3, 2017

First try ConstraintLayout

ConstraintLayout allows you to create large and complex layouts with a flat view hierarchy (no nested view groups). It's similar to RelativeLayout in that all views are layed out according to relationships between sibling views and the parent layout, but it's more flexible than RelativeLayout and easier to use with Android Studio's Layout Editor.



To use ConstraintLayout, make sure to install Support Repository of ConstraintLayout for Android and Solver for ConstraintLayout in Android SDK Manager:


Add dependency of ConstraintLayout library in your module-level build.gradle file:


dependencies {
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
}



In the toolbar or sync notification, click Sync Project with Gradle Files.

We can convert an existing layout to a constraint layout in Android Studio's Layout Editor:
- Open your layout in Android Studio and click the Design tab at the bottom of the editor window.
- In the Component Tree window, right-click the layout and click Convert layout to ConstraintLayout.

After finished, the helloworld default layout converted to:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.blogspot.android_er.androidconstraintlayout.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        tools:layout_constraintTop_creator="1"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>


This video show howto, step-by-step:


Reference:
Build a Responsive UI with ConstraintLayout

More:
Building interfaces with ConstraintLayout in Android Studio