Monday 16 February 2015

You Tube Player Activity

YouTubePlayerActivity

Simply pass a url to play youtube video on new activity. It supports screen orientation, media volume control and etc.

Set Up AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

<activity
    android:name="com.thefinestartist.ytpa.YouTubePlayerActivity"
    android:configChanges="keyboardHidden|orientation|screenSize"
    android:screenOrientation="sensor"
    android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" />

<meta-data
    android:name="com.thefinestartist.ytpa.YouTubePlayerActivity.ApiKey"
    android:value="your_google_api_key" />

Usage

Intent intent = new Intent(MainActivity.this, YouTubePlayerActivity.class);

// Youtube video ID or Url (Required)
intent.putExtra(YouTubePlayerActivity.EXTRA_VIDEO_ID, "iS1g8G_njx8");
// These kind of url can be parsed!!
// https://youtu.be/iS1g8G_njx8
// https://www.youtube.com/watch?v=iS1g8G_njx8
// https://www.youtube.com/watch?v=iS1g8G_njx8&vq=hd1080
intent.putExtra(YouTubePlayerActivity.EXTRA_VIDEO_URL, "https://youtu.be/iS1g8G_njx8");

// Show audio interface when user adjust volume
// true for default
intent.putExtra(YouTubePlayerActivity.EXTRA_SHOW_AUDIO_UI, true);

// If the video is not playable, use Youtube app or Internet Browser to play it
// true for default
intent.putExtra(YouTubePlayerActivity.EXTRA_HANDLE_ERROR, true);

// Animation when closing youtubeplayeractivity (none for default)
intent.putExtra(YouTubePlayerActivity.EXTRA_ANIM_ENTER, R.anim.fade_in);
intent.putExtra(YouTubePlayerActivity.EXTRA_ANIM_EXIT, R.anim.fade_out);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

YoutubeUrlParser

This util helps to retrieve youtube video id from youtube url or vice versa. Reference
String vidoeId = YoutubeUrlParser.getVideoId(videoUrl);
String vidoeUrl = YoutubeUrlParser.getVideoId(videoId);

Wonder Adapter

WonderAdapter

How many times do you copy ArrayAdapter, CursorAdapter and ViewHolders code? I've developed this library based mostly on the idea of UniversalAdapter library, but I've implemented a few improvements like ViewHolder pattern, multi view and cursor compatibility.

Usage

You just have to use the adapter that fits better to your needs. For now, there are only 3 wonder adapters you can use:
  • WArrayAdapter
  • WBaseAdapter
  • WCursorAdapter
Steps to use any of these adapters within a ListView:
  1. Create Custom Holder and let implement SingleWonder, MultiWonder or CursorWonder depending on the Adapter we want to use with. ..* T is the class of the item we want to show. ..* W the Holder class.
  2. Basic methods to implement (on single views): ..* W newInstance() returns an instance of W(holder) for every row in the list. Our holder contains row view fields initialized. ..*void bind(...) needed to draw desired object fields on the initialized view fields contained inside our class W. ..* View inflateView(...) needs explanation? :-).
Example: ListView with array list of items within a single row view
WArrayAdapter<Wonder, SingleViewHolder> adapter = new WArrayAdapter(this, getData(cursor), new SingleViewHolder());
listView.setAdapter(adapter);
and our SingleViewHolder implementation:
public class SingleViewHolder implements SingleWonder<Wonder, SingleViewHolder> {

  // UI
  @InjectView(R.id.row_wonder_image) ImageView imageView;
  @InjectView(R.id.row_wonder_title) TextView titleView;

  @Override public SingleViewHolder newInstance() {
    return new SingleViewHolder();
  }

  @Override public void bind(Context context, Wonder item) {
    Picasso.with(context).load(item.getImage()).into(imageView);
    titleView.setText(item.getTitle());
  }

  @Override public View inflateView(LayoutInflater inflater, ViewGroup parent) {
    View view = inflater.inflate(R.layout.row_wonder, parent, false);
    ButterKnife.inject(this, view);
    return view;
  }

}
I've used Jake Wharton's Butterknife library to avoid using findViewById on every view in our row layout :-)
Check the code for full demo samples.

Crop Image View

CropImageView

An ImageView that supports different kind of cropping rather than the only Android is currently supporting: centerCrop
Using this library, you can crop your desired image by sides described below:
Crop options
Development idea borns at the point in [Kerad Games] we needed images cropped by somewhere no matter the image size.

Usage

Step 1

Gradle
dependencies {
   compile 'com.cesards.android:cropimageview:1.0.0'
}
Maven
<dependency>
   <groupId>com.cesards.android</groupId>
   <artifactId>cropimageview</artifactId>
   <version>1.0.0</version>
   <type>aar</type>
</dependency>

Step 2

Define in xml:
<com.cesards.cropimageview
   xmlns:custom="http://schemas.android.com/apk/res-auto"
   android:id="@+id/imageView1"
   android:src="@drawable/photo1"
   custom:crop="value" />
where value can take values
topLeft|centerLeft|bottomLeft|topRight|centerRight|bottomRight|centerTop|centerBottom
Or in code:
CropImageView cropImageView = new CropImageView(CropActivity.this);
final Resources res = getResources();
cropImageView.setImageDrawable(res.getDrawable(images[position]));
final CropImageView.CropType cropType = imageCrops[position];
cropImageView.setCropType(cropType);

Friday 13 February 2015

Image Blurring

ImageBlurring

Android Blurring Image (Bitmap) By Java And JNI.

Use

  • RenderScript
    • Call Android's RenderScript to blur image
    • Speed is generally, with direct blur little difference in the Java layer
    • This need Android >= 4.4
  • Fast Blur
    • Call Java class to blur iamge
    • Fast Blur is blurring project's methods
    • Fast Blur is stack blur
  • JniArray
    • Fuzzy method is blur C language implementation of the stack blur
    • After the blur JNI layer, and then back to the blur data
    • In the Java layer of class parsed pixel array passed to JNI layer
    • After the blur back to the Array
  • JniBitMap
    • Fuzzy method is fuzzy C language implementation of the stack blur
    • After the blur JNI layer, and then back to the blur data
    • After the blur back to the Bitmap

Parallax View Pager

ParallaxViewPager

An easy-to-use ViewPager subclass with parallax background.
Setup requires little extra effort, using the ParallaxViewPager is just like using a standard ViewPager, with the same adapter. Of course, there's no silver bullet - the developer has to supply a background tailored to the current needs (eg. the number of items in the adapter and the size of the ViewPager). Check out this gif and this blog post to see what it's all about.
  1. Include it in your project as a Gradle dependency:
  2.     dependencies {
            compile 'com.andraskindler.parallaxviewpager:parallaxviewpager:0.3.1'
        }
    
    1. Create a ParallaxViewPager programmatically or in a layout xml.
    2. Set the background via xml or one of the following methods:
      • setBackgroundResource(int resid)
      • setBackground(Drawable background) or setBackgroundDrawable(Drawable background)
      • setBackground(Bitmap bitmap)
    3. (Optional) Specify how the view should scale the background with the setScaleType(final int scaleType) method. Choose from the following parameters:
      • FIT_HEIGHT means the height of the image is resized to matched the height of the View, also stretching the width to keep the aspect ratio. The non-visible part of the bitmap is divided into equal parts, each of them sliding in at the proper position. This is the default value.
      • FIT_WIDTH means the width of the background image is divided into equal chunks, each taking up the whole width of the screen. This mode is not the usual parallax-effect, as the speed of the background scrolling equals the speed of the views.
    4. (Optional) Set the amount of overlapping with the setOverlapPercentage(final float percentage) method. This is a number between 0 and 1, the smaller it is, the slower is the background scrolling. The default value is 50 percent. This only works with FIT_HEIGHT.

An example, inside the 
onCreate() of an activity:

  1.     //...
        final ParallaxViewPager parallaxViewPager = new ParallaxViewPager(this);
        parallaxViewPager.setAdapter(new MyPagerAdapter());
        parallaxViewPager.setBackgroundResource(R.drawable.nagy);
        setContentView(parallaxViewPager);
        //...

Circle Avatar Image View

DSAvataImageView

Subclass of ImageView to create a circle avatar image view with user name initial image view.

XML (Use Circle avatar image view)

    <com.xperi.avataimageview.DSAvatarImageView
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:src="@drawable/image"
        app:border_color="#EEEEEE"
        app:border_width="5dp"
        />

XML (Use user name initial view) output 'SJ'


    <com.xperi.avataimageview.DSAvatarImageView
        android:layout_width="250dp"
        android:layout_height="250dp"
        app:border_color="#EEEEEE"
        app:border_width="5dp"
        app:name="steve jobs"
        app:background_color="@android:color/white"
        app:text_color="@android:color/black"
        />
You may use the following properties in your XML to customize your DSAvataImageView.

Properties:
  • app:border (boolean) -> default true
  • app:border_color (color) -> default GRAY
  • app:border_width (dimension) -> default 2dp
  • app:name (String) -> default
  • app:background_color (color) -> default WHITE
  • app:text_color (color) -> default GRAY ###JAVA (Use Circle avatar image view)
    DSAvatarImageView avataImageView=getView(convertView, R.id.circularIv);
    avataImageView.setBorderColor(getResources().getColor(R.color.GrayLight));
    avataImageView.setBorderWidth(10);
    avataImageView.setImageResource(R.id.sample);

JAVA (Use user name initial view) output 'SJ'


    DSAvatarImageView avataImageView=getView(convertView, R.id.circularIv);
    avataImageView.setBorderColor(getResources().getColor(R.color.GrayLight));
    avataImageView.setName("steve jobs")

Android Twitter

AndroidTwitter

AndroidTwitter is a small android library to let you connect to Twitter and access all it's public API (tweet status, retweet, etc).

How to Use

public class TestConnect extends Activity {
    private TwitterApp mTwitter;
    private CheckBox mTwitterBtn;

    private static final String twitter_consumer_key = "xxx";
    private static final String twitter_secret_key = "xxxx";

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

        setContentView(R.layout.main);

        mTwitterBtn = (CheckBox) findViewById(R.id.twitterCheck);

        mTwitterBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onTwitterClick();
            }
        });

        mTwitter    = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);

        mTwitter.setListener(mTwLoginDialogListener);

        if (mTwitter.hasAccessToken()) {
            mTwitterBtn.setChecked(true);

            String username = mTwitter.getUsername();
            username        = (username.equals("")) ? "Unknown" : username;

            mTwitterBtn.setText("  Twitter (" + username + ")");
            mTwitterBtn.setTextColor(Color.WHITE);
        }

        Button goBtn = (Button) findViewById(R.id.button1);

        goBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(TestConnect.this, TestPost.class));
            }
        });
    }

    private void onTwitterClick() {
        if (mTwitter.hasAccessToken()) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);

            builder.setMessage("Delete current Twitter connection?")
                   .setCancelable(false)
                   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           mTwitter.resetAccessToken();

                           mTwitterBtn.setChecked(false);
                           mTwitterBtn.setText("  Twitter (Not connected)");
                           mTwitterBtn.setTextColor(Color.GRAY);
                       }
                   })
                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();

                            mTwitterBtn.setChecked(true);
                       }
                   });
            final AlertDialog alert = builder.create();

            alert.show();
        } else {
            mTwitterBtn.setChecked(false);

            mTwitter.authorize();
        }
    }

    private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
        @Override
        public void onComplete(String value) {
            String username = mTwitter.getUsername();
            username        = (username.equals("")) ? "No Name" : username;

            mTwitterBtn.setText("  Twitter  (" + username + ")");
            mTwitterBtn.setChecked(true);
            mTwitterBtn.setTextColor(Color.WHITE);

            Toast.makeText(TestConnect.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(String value) {
            mTwitterBtn.setChecked(false);

            Toast.makeText(TestConnect.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
        }
    };
}