Sep 22, 2012

Get color-int from alpha, red, green, blue components

Android system's android.graphics.Color class provide methods for creating and converting color ints.


Sep 20, 2012

Create Spinner from String array

To create Spinner from String array:

Create Spinner from String array


package com.example.androidspinner;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {
 
 Spinner mySpinner;
 
 String[] spinnerArray ={ "One", "Two", "Three", "Four", "Five"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mySpinner = (Spinner)findViewById(R.id.myspinner);

        ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<String>(
          this, 
          android.R.layout.simple_spinner_item, 
          spinnerArray);
        myArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item );

        mySpinner.setAdapter(myArrayAdapter);
        
        mySpinner.setOnItemSelectedListener(myOnItemSelectedListener);
    }

    OnItemSelectedListener myOnItemSelectedListener
    = new OnItemSelectedListener(){

  @Override
  public void onItemSelected(AdapterView<?> parent, View view, int position,
    long id) {
   String selectedItem = (String) parent.getItemAtPosition(position);
   Toast.makeText(
     getApplicationContext(), 
     selectedItem, 
     Toast.LENGTH_LONG)
     .show();
   
  }

  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
   // TODO Auto-generated method stub
   
  }};

}


Sep 10, 2012

Home Screen Widget step-by-step - Implement OnClick PendingIntent for Widget

It's part of the Home Screen Widgets step-by-step series.

We can cureat PendingIntent, and register it to widget's RemoteViews by setOnClickPendingIntent() method. As a result, when user click on the assigned view in the widgets, the PendingIntent will be trigged and to do something.

In the example, my blog (http://android-coding.blogspot.com/) will be opened once user click on the ID in widgets.

Implement OnClick PendingIntent for Widget


Modify configure activity (ConfigureWidgetActivity.java) and App Widget Provider (WidgetProvider.java) to Prepare PendingIntent for remoteViews OnClickListener.

ConfigureWidgetActivity.java
package com.example.androidhomewidget;

import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.TextView;

public class ConfigureWidgetActivity extends Activity {
 
 int appWidgetId;
 Button configureOkButton;
 TextView wId;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.configure_layout);
  wId = (TextView)findViewById(R.id.wid);
  configureOkButton = (Button)findViewById(R.id.confighreok);
  configureOkButton.setOnClickListener(configureOkButtonOnClickListener);
  
  Intent intent = getIntent();
  Bundle extras = intent.getExtras();
  
  if (extras != null) {
   appWidgetId = extras.getInt(
     AppWidgetManager.EXTRA_APPWIDGET_ID,
     AppWidgetManager.INVALID_APPWIDGET_ID);
   
   wId.setText("appWidgetId = " + appWidgetId);
   
  }else{
   finish();
  }
      
 }
 
 OnClickListener configureOkButtonOnClickListener
 = new OnClickListener(){

  @Override
  public void onClick(View v) {

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());

    RemoteViews remoteViews = new RemoteViews(
      getApplicationContext().getPackageName(), 
      R.layout.widget_layout);
    
    remoteViews.setTextViewText(R.id.widget_id, String.valueOf(appWidgetId));
    remoteViews.setTextViewText(R.id.widget_status, "Waiting...");
    
    //--- Prepare PendingIntent for remoteViews OnClickListener
    String myBlog = "http://android-coding.blogspot.com/";
    Uri Uri_myBlog = Uri.parse(myBlog);
    Intent clickIntent = new Intent(Intent.ACTION_VIEW, Uri_myBlog);
    
    int pendingRequestCode = 0;
    int pendingFlag = 0;
    PendingIntent pendingIntent
     = PendingIntent.getActivity(
       getApplicationContext(), 
       pendingRequestCode, 
       clickIntent, 
       pendingFlag);
    remoteViews.setOnClickPendingIntent(R.id.widget_id, pendingIntent);
    //--- End of Prepare PendingIntent
    
    appWidgetManager.updateAppWidget(appWidgetId, remoteViews);

    Intent intent = new Intent();
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    setResult(RESULT_OK, intent);
    finish();
   
  }};

}


WidgetProvider.java
package com.example.androidhomewidget;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.RemoteViews;
import android.widget.Toast;

public class WidgetProvider extends AppWidgetProvider {

 @Override
 public void onDeleted(Context context, int[] appWidgetIds) {
  // TODO Auto-generated method stub
  super.onDeleted(context, appWidgetIds);
 }

 @Override
 public void onDisabled(Context context) {
  // TODO Auto-generated method stub
  super.onDisabled(context);
 }

 @Override
 public void onEnabled(Context context) {
  // TODO Auto-generated method stub
  super.onEnabled(context);
 }

 @Override
 public void onReceive(Context context, Intent intent) {
  // TODO Auto-generated method stub
  super.onReceive(context, intent);
 }

 @Override
 public void onUpdate(Context context, AppWidgetManager appWidgetManager,
   int[] appWidgetIds) {
  
  for(int i = 0; i < appWidgetIds.length; i++){
   
   int id = appWidgetIds[i];
   
   Toast.makeText(context, 
     "onUpdate: " + String.valueOf(id), 
     Toast.LENGTH_LONG).show();
   
   RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
   
   remoteViews.setTextViewText(R.id.widget_id, String.valueOf(id));
   
   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss");
   String now = simpleDateFormat.format(new Date());
   remoteViews.setTextViewText(R.id.widget_status, now);
   
   //--- Prepare PendingIntent for remoteViews OnClickListener
    String myBlog = "http://android-coding.blogspot.com/";
    Uri Uri_myBlog = Uri.parse(myBlog);
    Intent clickIntent = new Intent(Intent.ACTION_VIEW, Uri_myBlog);
    
    int pendingRequestCode = 0;
    int pendingFlag = 0;
    PendingIntent pendingIntent
     = PendingIntent.getActivity(
       context, 
       pendingRequestCode, 
       clickIntent, 
       pendingFlag);
    remoteViews.setOnClickPendingIntent(R.id.widget_id, pendingIntent);
    //--- End of Prepare PendingIntent
   
   appWidgetManager.updateAppWidget(id, remoteViews);
   
   super.onUpdate(context, appWidgetManager, appWidgetIds);
  }
 }

}



Sep 9, 2012

Home Screen Widget step-by-step - custom background shape of Widget

It's part of the Home Screen Widgets step-by-step series.

To custom background shape of Home Screen Widget, we can create custom background shape XML file, then apply it to the widget layout. (Actually it's same as define custom background in normal layouts.)

custom background shape of Widget


Create /res/drawable/round_rect.xml to define custom background shape.
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="5dp"
        android:color="#000000"/>
    <padding 
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/>
    <corners 
        android:radius="10dp"/>
</shape>


Modify the widget layout, /res/layout/widget_layout.xml, to apply android:background="@drawable/round_rect".
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/round_rect">
    <TextView
        android:id="@+id/widget_id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:background="#F06030"
        android:textColor="#101010"
        android:textSize="30sp"
        android:text="id"/>
    <TextView
        android:id="@+id/widget_status"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/background_dark"
        android:textColor="@android:color/white"
        android:textSize="30sp"
        android:text="status"/>
</LinearLayout>



Sep 4, 2012

Home Screen Widget step-by-step - resizeable home screen widget

It's part of the Home Screen Widgets step-by-step series.

Start from Android 3.1, API Level 12, support resizeable home screen widget. To specify a Home Screen Widget as resizeable, include android:resizeMode in App widget provider XML, /res/xml/widgetproviderinfo.xml in our example.

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="146dp"
    android:minHeight="72dp"
    android:updatePeriodMillis="1800000"
    android:initialLayout="@layout/widget_layout"
    android:configure="com.example.androidhomewidget.ConfigureWidgetActivity"
    android:resizeMode="horizontal|vertical">
</appwidget-provider>


Resizeable Home Screen Widget


To resize the widget, touch-hold it to show its resize handles, then drag the horizontal and/or vertical handles to change the size on the layout grid.


Sep 3, 2012

Home Screen Widget step-by-step - implement configure activity

It's part of the Home Screen Widgets step-by-step series.

In the previous articles, we have NO android:configure defined in our App widget provider XML, /res/xml/widgetproviderinfo.xml. So, the App Widget Provider will be called when user add our widget. Optionally we can implement our Configure Activity, it will be called at the first time user add the Widget, instead of App Widget Provider. Such that user can do something when he add the widget.

Configure Activity



Modify /res/xml/widgetproviderinfo.xml to add android:configure="com.example.androidhomewidget.ConfigureWidgetActivity".
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="146dp"
    android:minHeight="72dp"
    android:updatePeriodMillis="1800000"
    android:initialLayout="@layout/widget_layout"
    android:configure="com.example.androidhomewidget.ConfigureWidgetActivity">
</appwidget-provider>


ConfigureWidgetActivity.java
package com.example.androidhomewidget;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.TextView;

public class ConfigureWidgetActivity extends Activity {
 
 int appWidgetId;
 Button configureOkButton;
 TextView wId;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.configure_layout);
  wId = (TextView)findViewById(R.id.wid);
  configureOkButton = (Button)findViewById(R.id.confighreok);
  configureOkButton.setOnClickListener(configureOkButtonOnClickListener);
  
  Intent intent = getIntent();
  Bundle extras = intent.getExtras();
  
  if (extras != null) {
   appWidgetId = extras.getInt(
     AppWidgetManager.EXTRA_APPWIDGET_ID,
     AppWidgetManager.INVALID_APPWIDGET_ID);
   
   wId.setText("appWidgetId = " + appWidgetId);
   
  }else{
   finish();
  }
      
 }
 
 OnClickListener configureOkButtonOnClickListener
 = new OnClickListener(){

  @Override
  public void onClick(View v) {

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());

    RemoteViews remoteViews = new RemoteViews(
      getApplicationContext().getPackageName(), 
      R.layout.widget_layout);
    
    remoteViews.setTextViewText(R.id.widget_id, String.valueOf(appWidgetId));
    remoteViews.setTextViewText(R.id.widget_status, "Waiting...");
    
    appWidgetManager.updateAppWidget(appWidgetId, remoteViews);

    Intent intent = new Intent();
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    setResult(RESULT_OK, intent);
    finish();
   
  }};

}


Create /res/layout/configure_layout.xml to define the layout of the configure activity.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Widget Configure Activity" />
    <TextView
        android:id="@+id/wid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/confighreok"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="OK" />

</LinearLayout>


Modify AndroidManifest.xml to add <activity> of ConfigureWidgetActivity.java.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidhomewidget"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
<!-- define Widget Provider Receiver -->        
        <receiver android:name=".WidgetProvider" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
        <meta-data android:name="android.appwidget.provider"
            android:resource="@xml/widgetproviderinfo" />
        </receiver>

<!--  define Configure Activity -->
        <activity android:name=".ConfigureWidgetActivity">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
            </intent-filter>
        </activity>
        
    </application>

</manifest>



Infolinks In Text Ads