'Android > GUI & Activity' 카테고리의 다른 글

앱 최신버전 체크하는 방법  (0) 2014.11.19
Animation 종류  (0) 2014.10.28
[펌[] Android ActionBar 활용  (0) 2014.10.22
AutoScaleTextView 추천 소스  (0) 2014.10.16
AutoScale TextView (4.4버전 테스트완료)  (0) 2014.10.15

출처 : http://202psj.tistory.com/571


http://code.google.com/p/android-market-api/ 

 

개발자 입장에서 쌔가빠지게 업데이트 게속 해줘도

 

업데이트 하나도 안하는 사용자들이 너무 많다!!

 

주위에 보면 그런 사람 잇더라..

 

그렇다고 따로 서버 둬서 체크하자니까 그냥 앱혼자노는 어플은 부담스럽다

 

구글플레이에 돈주고 개발자 등록했는데 요정도 서비스는 해줘야하는거 아닌가~~

 

 

그렇다 해준다.

 

버전체크 api를 이용해서

 

정보를 가져와서 사용하자~

 

Build.VERSION.SDK_INT 일케 가져온담에 맞춰서 하자

 

 MarketSession session = new MarketSession();
   session.login("id","pw"); // 구글 아무 계정이나 되는듯..?
//   session.getContext.setAndroidId(myAndroidId);

   String query = "com.kwon.kwonyangsanbus"; // 앱 이름 또는 패키지 명 다 쿼리 되는듯.. 근데 내꺼 안뜨냐 ?
   AppsRequest appsRequest = AppsRequest.newBuilder()
                                   .setQuery(query)
                                   .setStartIndex(0).setEntriesCount(10)
                                   .setWithExtendedInfo(true)
                                   .build();

   session.append(appsRequest, new Callback<AppsResponse>() {
            @Override
            public void onResult(ResponseContext context, AppsResponse response) {
                     // Your code here
                     // response.getApp(0).getCreator() ...
                     // see AppsResponse class definition for more infos
             Logger.error("앱갯수 : "+response.getAppCount());
             for(int i = 0 ; i < response.getAppCount(); i++){
              Logger.error(i+"  "+response.getApp(i).getTitle());
              Logger.error(i+"  "+response.getApp(i).getCreator());
              Logger.error(i+"  "+response.getApp(i).getPackageName());
              Logger.error(i+"  "+response.getApp(i).getVersion());
              Logger.error(i+"  "+response.getApp(i).getVersionCode());
             }
            }
   });
   session.flush();



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

출처: http://diyall.tistory.com/846


[안드로이드] 안드로이드 APK 버전 체크하기

 

안드로이드의 APK 버전을 체크해서 요즘은 업데이트 여부를 알려주고 있습니다.

그래서 저도 시도해 볼려고 하니.. 여러가지 어렵더군요.

 

우선! 설치되어 있는 APK 의 버전은 쉽게 얻을 수 있습니다.

 

    public static String getVersionName(Context context) {
    	Log.i(TAG, "here in getVersionName");
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (NameNotFoundException e) {
        	Log.i(TAG, "err NameNotFoundException -> " + e.toString());
            return null;
        }
    }

 

 

하지만 문제는 마켓에 올린 최신버전과 비교를 하는 문제였습니다.

 

방법은

1. 서버를 운영하여 서버에 최신버전 내용을 넣고 비교하는 방법

2. 마켓의 내용을 HTML 파싱하는 방법 등이 있는 것 같습니다.

하지만.. 아직 초보를 그것도 쉽지 않더군요.

 

그러다가 찾은 방법이 구글에서 제공하는 Google Market API 를 이용하는 방법입니다.

하지만 query 부분에 패키지명을 넣으면 해결될 줄 알았는데.. 계속 null 값을 반환합니다.

 

임의적으로 "maps" 등의 단어를 넣으면 데이타를 가져올 수는 있는데.. 뿌려주는 결과값이 왜 그렇게 나오는지를 알수가 없었습니다.

 

마켓에서 "maps" 로 검색한 것과는 다른 결과를 보여주기 때문입니다.

 

그러다가.. 문제를 해결 하였습니다.

 

저와 같은 고민을 하는 사람들이 많은 것 같아서.. 포스트 남깁니다.

 

AndroidId 값 가져오는 방법

 

    private static final Uri URI = Uri.parse("content://com.google.android.gsf.gservices");
    private static final String ID_KEY = "android_id";
     
    static String getAndroidId(Context context) {
    	Log.i(TAG, "here in getAndroidId");
        String[] params = { ID_KEY };
        Cursor c = context.getContentResolver()
                .query(URI, null, null, params, null);
     
        if (!c.moveToFirst() || c.getColumnCount() < 2)
            return null;
     
        try {
        	Log.i(TAG, "getAndroidId() : " + Long.toHexString(Long.parseLong(c.getString(1))));
            return Long.toHexString(Long.parseLong(c.getString(1)));
        } catch (NumberFormatException e) {
            return null;
        }
    }

AndroidManifest.xml 안에 권한을 넣어줘야 함

 

 

마켓의 정보 가져오기

 

    public static String getMarketVersionName(Context context) {
    	Log.i(TAG, "here in getMarketVersionName");
    	
    	try {
    		MarketSession session = new MarketSession();
        	session.login(email, pass);
        	//Log.i(TAG, "session : "+session.getAuthSubToken());
        	session.getContext().setAndroidId(getAndroidId(context));
        	String query = "패키지명";
        	
        	AppsRequest appsRequest = AppsRequest.newBuilder()
        			.setQuery(query)
        			.setStartIndex(0).setEntriesCount(1)
        			.setOrderType(AppsRequest.OrderType.NEWEST)
        			.setWithExtendedInfo(false)
        			.build();
        	
        	session.append(appsRequest, new Callback() {

    			@Override
    			public void onResult(ResponseContext context, AppsResponse response) {
    				//Log.i(TAG, "getAppCount() : " + response.getAppCount());
    				for (int i=0; i " + e.toString());
    	}
    	
    	return marketVersion;
    }

 

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

import com.gc.android.market.api.MarketSession;
import com.gc.android.market.api.MarketSession.Callback;
import com.gc.android.market.api.model.Market.AppsRequest;
import com.gc.android.market.api.model.Market.AppsResponse;
import com.gc.android.market.api.model.Market.ResponseContext;


위 마켓 api를 사용하기 위해 필요한 파일

파일에 최신버전은

http://code.google.com/p/android-market-api/

이쪽에서 왼쪽측 download 를 보면 받을수 있다.


 androidmarketapi-0.6.jar

 protobuf-java-2.2.0.jar

////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: http://www.androidside.com/plugin/mobile/board.php?bo_table=B49&wr_id=75819

@android:anim/accelerate_decelerate_interpolator
 
        애니메이션이 점점 빠르게 동작하다가 점점 천천히 동작합니다.
 
 
    @android:anim/accelerate_interpolator
 
        애니메이션이 점점 빠르게 동작합니다.
 
 
    @android:anim/anticipate_interpolator
 
        애니메이션이 시작할 때 반대 방향으로 동작을 한 후에 본래의 방향으로 동작합니다.
 
 
    @android:anim/anticipate_overshoot_interpolator
 
        애니메이션이 시작할 때 반대 방향으로 동작을 한 후에 종료 지점을 지나갔다가 종료 지점으로
        돌아옵니다. 예를 들어 왼쪽에서 오른쪽으로 이동하는 애니메이션이 있다면 시작할 때 뷰가
        왼쪽으로 조금 움직인 후 오른쪽으로 이동하고, 원래 도착해야할 위치를 지났다가 다시 왼쪽으로
        이동합니다.
 
 
    @android:anim/bounce_interpolator
 
        애니메이션이 종료될 때 튕기면서 스프링 효과를 표현합니다.
 
 
    @android:anim/cycle_interpolator
  
        애니메이션을 동작한 후에 반대 방향으로 한번 더 동작합니다. 만약 오른쪽으로 50 위치까지
        이동하는 애니메이션에 이 효과가 적용되면 오른쪽으로 50 만큼 이동한 후에 왼쪽으로 -50
        위치까지 이동하게됩니다.
       
       
    @android:anim/decelerate_interpolator
 
        애니메이션의 움직임이 점점 느려집니다.
 
 
    @android:anim/linear_interpolator
 
        특별한 효과 없이 일정하게 애니메이션이 동작합니다.
 
 
    @android:anim/overshoot_interpolator
 
        애니메이션이 동작할 때 멈춰야할 위치를 지난 후에 다시 돌아옵니다.


출처 : http://www.vogella.com/tutorials/AndroidActionBar/article.html


Using the action bar in Android applications

This tutorial describes how to use the action bar in your Android applications. It is based on Eclipse 4.3 (Kepler), Java 1.6 and Android 4.4.


Table of Contents

1. Introduction to the action bar
1.1. What is the action bar?
1.2. Example
1.3. Action bar on devices before API 3.0
2. Using the ActionBar
2.1. Entries in the action bar (actions)
2.2. Creating actions
2.3. Reacting to action selection
2.4. Search an action in the action bar
2.5. Changing the menu
3. Customizing the action bar
3.1. Changing the visibility of the action bar
3.2. Assigning a Drawable
3.3. Dimming the navigation buttons
3.4. Using Immersive Full-Screen Mode
3.5. Enabling the split action bar
4. Contributing to the action bar with fragments
5. Making the action bar dynamic
5.1. Custom views in the action bar
5.2. Contextual action mode
5.3. Action view
6. Action provider
6.1. What is an action provider?
6.2. Example: usage of the ShareActionProvider
7. Navigation via the application icon
7.1. Application icon as home
7.2. Application icon as Up button
8.
8.1. Navigation drawer
8.2. Example: Using the navigation drawer
8.3. Tab navigation
8.4. Dropdown menu navigation
8.5. Evaluation
9. Exercise: ActionBar
9.1. Project
10. Exercise: Add an action bar to your application
10.1. Create an icon for the ActionBar
10.2. Add a menu XML resource
10.3. Add actions to your menu resource
10.4. Assign icons
10.5. Validate XML resource
10.6. Add the action bar to your activity
10.7. Run the application and test the action bar
10.8. Remove the refresh button
11. Exercise: Using the contextual action mode
12. Support this website
12.1. Thank you
12.2. Questions and Discussion
13. Links and Literature
13.1. Source Code
13.2. Android ActionBar Resources
13.3. vogella Resources

1. Introduction to the action bar

1.1. What is the action bar?

The action bar (ActionBar) is located at the top of the activity. It can display the activity title, icon, actions which can be triggered, additional views and other interactive items. It can also be used for navigation in your application.

The action bar is enabled for devices which specify a target SDK of API version 11 or higher. It is possible to disable the action bar via the used theme, but the default Android themes have it enabled.

Applications with a target SDK version less than API 11 use the options menu if such a button is present on the device. The option menu is displayed if the user presses the Option button. The action bar is superior to the options menu, as the action bar is clearly visible, while the options menu is only shown on request. In case of the options menu, the user may not recognize that options are available in the application.

1.2. Example

The following screenshot shows the action bar of the Google+ Android application with interactive items and a navigation bar. On top it also indicates that the user can open a navigation bar on the side of the application.

ActionBar Screenshot

1.3. Action bar on devices before API 3.0

The action bar has been introduced in Android 3.0. If you want to use the action bar on devices with an earlier Android release, you have two popular options.

First, you can use the Open Source project called ActionBar Sherlock which allows you to use the action bar on Android devices as of Android 1.6. You find this library under the following link.

http://actionbarsherlock.com 

The second option is to use the ActionBarCompat library from the Android support library v7, which supports the action bar as of Android 2.1. See the following link to setup the support library v7 in your project: Setting up the support library.

This section focuses on the description of using the action bar without the Open Source or support library. You can easily port your application to an earlier API version using one of the different libraries.

2. Using the ActionBar

2.1. Entries in the action bar (actions)

Entries in the action bar are typically called actions. While it is possible to create entries in the action bar via code, it is typically defined in an XML resource file.

Each menu definition is contained in a separate file in the res/menu folder. The Android tooling automatically creates a reference to this file in the R file, so that the menu resource can be accessed.

2.2. Creating actions

An activity adds entries to the action bar in its onCreateOptionsMenu() method.

The showAsAction attribute allows you to define how the action is displayed. For example, the ifRoom attribute defines that the action is only displayed in the action bar if there is sufficient screen space available.

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_refresh"
        android:orderInCategory="100"
        android:showAsAction="always"
        android:icon="@drawable/ic_action_refresh"
        android:title="Refresh"/>
    <item
        android:id="@+id/action_settings"
        android:title="Settings">
    </item>

</menu> 

The MenuInflator class allows to inflate actions defined in an XML file and adds them to the action bar.MenuInflator can get accessed via the getMenuInflator() method from your activity. The following example code demonstrates the creation of actions.

@Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);
    return true;
  } 

Tip

While you can define the actions also in your source code, it is good practice to do this via XML files, as this results in less boilerplate code.

2.3. Reacting to action selection

If an action is selected, the onOptionsItemSelected() method in the corresponding activity is called. It receives the selected action as parameter. Based on this information, you can decide what to do. The usage of this method is demonstrated in the following code snippet.

@Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // action with ID action_refresh was selected
    case R.id.action_refresh:
      Toast.makeText(this, "Refresh selected", Toast.LENGTH_SHORT)
          .show();
      break;
    // action with ID action_settings was selected
    case R.id.action_settings:
      Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT)
          .show();
      break;
    default:
      break;
    }

    return true;
  } 

2.4. Search an action in the action bar

To search for a menu item in a menu you can use the findItem() method of the Menu class. This method allows to search by id.

2.5. Changing the menu

The onCreateOptionsMenu() method is only called once. If you want to change the menu later, you have to call theinvalidateOptionsMenu() method. Afterwards this onCreateOptionsMenu() method is called again.

3. Customizing the action bar

3.1. Changing the visibility of the action bar

You can change the visibility of the action bar at runtime. The following code demonstrates that.

ActionBar actionBar = getActionBar();
actionBar.hide();
// more stuff here...
actionBar.show(); 

You can also change the text which is displayed alongside the application icon at runtime. The following example shows that.

ActionBar actionBar = getActionBar();
actionBar.setSubtitle("mytest");
actionBar.setTitle("vogella.com"); 

3.2. Assigning a Drawable

You also add a Drawable to the action bar as background via the ActionBar.setBackgroundDrawable() method.

The action bar scales the image. Therefore it is best practice to provide a scalable drawable , e.g., a 9-patch or XML drawable.

Tip

As of Android 4.2 the background of the action bar can also be animated via anAnimationDrawable.

3.3. Dimming the navigation buttons

You can also dim the software navigation button in your Android application to have more space available. If the user touches the button of the screen, the navigation button is automatically shown again.

Dimming the navigation buttons is demonstrated by the following code snippet.

getWindow().
  getDecorView().
  setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); 

The following screenshots show an application with and without the navigation buttons.

Application with action bar

Application with dimmed action bar

3.4. Using Immersive Full-Screen Mode

As of Android 4.4 (API 19) you can put your application into full screen mode. The first time this happens the system displays the user the info that he can restore the system bars with a downward swipe along the region where the system bars normally appear.

For example the following method also to put an activity into full screen mode.

// This method hides the system bars and resize the content
  private void hideSystemUI() {
    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
            | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
            // remove the following flag for version < API 19
            | View.SYSTEM_UI_FLAG_IMMERSIVE); 
  } 

3.5. Enabling the split action bar

You can define that the action bar should be automatically split by the system if not enough space is available.

You can activate this via the android:uiOptions="SplitActionBarWhenNarrow" parameter in the declaration of your application activity in the AndroidManifest.xml file.

Note

If this option is activated, Android has the option to split the action bar. Whether to split is decided by the system at runtime.

4. Contributing to the action bar with fragments

Fragments can also contribute entries to the action bar.

To do this, call setHasOptionsMenu(true) in the onCreate() method of the fragment. The Android framework calls in this case the onCreateOptionsMenu() method in the fragment class and adds its menu items to the ones added by the activity .

5. Making the action bar dynamic

5.1. Custom views in the action bar

You can also add a custom view to the action bar, for example, a button or a text field.

For this you use the setCustomView method of the ActionView class. You also have to enable the display of custom views via the setDisplayOptions() method by passing in the ActionBar.DISPLAY_SHOW_CUSTOM flag.

For example, you can define a layout file which contains a EditText element.

<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/searchfield"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:inputType="textFilter" >

</EditText> 

This layout can be assigned in an activity to the action bar via the following code. The example code also attaches a listener to the custom view.

package com.vogella.android.actionbar.customviews;

import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class MainActivity extends Activity {

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

    ActionBar actionBar = getActionBar();
    // add the custom view to the action bar
    actionBar.setCustomView(R.layout.actionbar_view);
    EditText search = (EditText) actionBar.getCustomView().findViewById(R.id.searchfield);
    search.setOnEditorActionListener(new OnEditorActionListener() {

      @Override
      public boolean onEditorAction(TextView v, int actionId,
          KeyEvent event) {
        Toast.makeText(MainActivity.this, "Search triggered",
            Toast.LENGTH_LONG).show();
        return false;
      }
    });
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
        | ActionBar.DISPLAY_SHOW_HOME);
  }

} 

5.2. Contextual action mode

A contextual action mode activates a temporary action bar that overlays the application action bar for the duration of a particular sub-task.

The contextual action mode is typically activated by selecting an item or by long clicking on it.

To implement this, call the startActionMode() method on a view or on your activity. This method gets anActionMode.Callback object which is responsible for the life cycle of the contextual action bar.

You could also assign a context menu to a view via the registerForContextMenu(view) method. A context menu is also activated if the user "long presses" the view. The onCreateContextMenu() method is called every time a context menu is activated as the context menu is discarded after its usage. You should prefer the contextual action mode over the usage of context menus.

5.3. Action view

An action view is a widget that appears in the action bar as a substitute for an action item's button. You can, for example, use this feature to replace an action item with a ProgressBar view. An action view for an action can be defined via the android:actionLayout or android:actionViewClass attribute to specify either a layout resource or widget class to use.

This replacement is depicted in the following screenshots.

Before activating the ActionView

ActionViews running

The following activity replaces the icon at runtime with an action view which contains a ProgressBar view.

package com.vogella.android.actionbar.progress;

import android.app.ActionBar;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

  private MenuItem menuItem;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ActionBar actionBar = getActionBar();
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
        | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_load:
      menuItem = item;
      menuItem.setActionView(R.layout.progressbar);
      menuItem.expandActionView();
      TestTask task = new TestTask();
      task.execute("test");
      break;
    default:
      break;
    }
    return true;
  }

  private class TestTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
      // Simulate something long running
      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      return null;
    }

    @Override
    protected void onPostExecute(String result) {
      menuItem.collapseActionView();
      menuItem.setActionView(null);
    }
  };
} 

The following code shows the layout used for the action view.

<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/progressBar2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

</ProgressBar> 

The following code shows the XML files for the menu.

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_settings"
        android:orderInCategory="100"
        android:showAsAction="always"
        android:title="Settings"
        />

    <item
        android:id="@+id/menu_load"
        android:icon="@drawable/navigation_refresh"
        android:orderInCategory="200"
        android:showAsAction="always"
        android:title="Load"/>

</menu> 

6. Action provider

6.1. What is an action provider?

An action provider defines rich menu interaction in a single component. It can generate action views, which are used in the action bar, dynamically populate sub-menus of an action and handle default action invocations.

The base class for an action provider is the ActionProvider class.

Currently the Android platform provides two action providers: the MediaRouteActionProvider and theShareActionProvider.

6.2. Example: usage of the ShareActionProvider

The following demonstrates the usage of the ShareActionProvider. This action provider allows you to grab selected content from applications which have registered the Intent.ACTION_SEND intent.

To use ShareActionProvider, you have to define a special menu entry for it and assign an intent which contains the sharing data to it.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

   <item android:id="@+id/menu_share"
          android:title="Share"
          android:showAsAction="ifRoom"
          android:actionProviderClass="android.widget.ShareActionProvider" />
    <item
        android:id="@+id/item1"
        android:showAsAction="ifRoom"
        android:title="More entries...">
    </item>

</menu> 

@Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);

    // Get the ActionProvider for later usage
    provider = (ShareActionProvider) menu.findItem(R.id.menu_share)
        .getActionProvider();
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_share:
      doShare();
      break;
    default:
      break;
    }
    return true;  
  }

  public void doShare() {
    // populate the share intent with data
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TEXT, "This is a message for you");
    provider.setShareIntent(intent);
  } 

7. Navigation via the application icon

7.1. Application icon as home

The action bar shows an icon of your application. This is called the home icon. You can assign an action to this icon. The recommendation is to return to the main activity in your program if the user selects this icon.

If the action is selected, the onOptionsItemSelected() method is called with an action which has theandroid.R.id.home ID.

Before Android 4.1, you had to use the android.R.id.home ID in the onOptionMenuItemSelected() method and enable the selection of the home button. This is demonstrated by the following code in which the SecondActivity activity defines the MainActivity as home.

package com.vogella.android.actionbar.homebutton;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;

public class SecondActivity extends Activity {

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

    // enable the home button
    ActionBar actionBar = getActionBar();
    actionBar.setHomeButtonEnabled(true);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
      Intent intent = new Intent(this, MainActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);
      break;
      // Something else
    case R.id.action_settings:
      intent = new Intent(this, ThirdActivity.class);
      startActivity(intent);
    default:
      break;
    }
    return super.onOptionsItemSelected(item);
  }

} 

Tip

As of Android 4.1 you can simply set the parentActivityName in theAndroidManifest.xml file pointing to the parent activity.

<activity
  android:name="SecondActivity"
  android:label="@string/app_name"
  android:parentActivityName="MainActivity" >
</activity> 

7.2. Application icon as Up button

You can use the application icon also as Up button, e.g., to go to the parent activity of the current activity. The back button on the device always returns to the previous activity.

Both can be different, for example, if the user started the option to write an email from the home screen, the back button will return the user to the home screen while the Up button would return the user to the activity which shows an overview of all emails.

To enable the Up display, you can use the following code snippet in your activity.

actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true); 

Note

This snippet only enables the Up display on your home icon. You need to implement the correct behavior in your activity in the onOptionsItemSelected() method. The corresponding action still has the android.R.id.home ID.

Warning

The difference between Up and the Back button can be confusing for the end user. If you decide to implement Up, in your application, it is recommended to perform some end user testing to see if the Up implementation is intuitive for them or not.

8.1. Navigation drawer

A relatively new navigation pattern is the navigation drawer. The navigation drawer is a panel that displays the navigation options on the left side of the screen. It is hidden by default, but can be displayed with a swipe from the left side to the right or if the user touches the app icon.

The usage of the navigation drawer in the Gmail application is depicted in the following screenshot.

Navigation Drawer in Gmail

The navigation drawer is part of the compatibility library v4. To use this navigation pattern, you create a layout with the android.support.v4.widget.DrawerLayout layout manager. This layout manager must contain only two child views. The first is the element for the main content and the second one the container for the drawer menu. The drawer menu is typically implemented with a ListView widget. Such a layout is demonstrated by the following snippet.

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!-- The navigation drawer -->
     <!-- should not be larger than 320 to show content -->
    <ListView android:id="@+id/left_drawer"
        android:layout_width="180dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</android.support.v4.widget.DrawerLayout> 

You can fill the ListView in your activity code and register a listener via the ListView.OnItemClickListern method on the list item. In this listener you can perform the navigation action. For example, you start a new activity or replace a fragment in your layout.

8.2. Example: Using the navigation drawer

The following example demonstrates the usage of the navigation drawer. If you want to follow this example, create a new Android project and ensure that the support library is added to it.

Tip

To add the support library to a project, right-click on the project and select Android Tools → Add Support Library from the context menu.

Create a layout file called fragment_layout based on the following listing.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="Placeholder Text"
        android:layout_gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout> 

Afterwards, create the OpertingSystemFragment class for the fragment.

package com.vogella.android.actionbar.navigationdrawer;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class OpertingSystemFragment extends Fragment {
  public static final String ARG_OS= "OS";
  private String string;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_layout, null);
    TextView textView = (TextView) view.findViewById(R.id.textView1);
    textView.setText(string);
    return view;
  }
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);  
  }
  @Override
  public void setArguments(Bundle args) {
    string = args.getString(ARG_OS);
  }
} 

Now add a few strings and a string array to your values/strings.xml file.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Navigationdrawer</string>
    <string name="action_settings">Settings</string>
    <string name="action_update">Update</string>
    <string name="drawer_open">Open Drawer</string>
    <string name="drawer_close">Close Drawer</string>
    <string name="hello_world">Hello world!</string>
    <string-array name="operating_systems">
        <item >Android</item>
        <item >iPhone</item>
        <item >Windows Mobile</item>
    </string-array>

</resources> 

Finally create the activity as follows.

package com.vogella.android.actionbar.navigationdrawer;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private String[] mPlanetTitles;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
  private ActionBarDrawerToggle mDrawerToggle;
  private CharSequence title;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        title = getActionBar().getTitle();
        mPlanetTitles = getResources().getStringArray(R.array.operating_systems);
        System.out.println(mPlanetTitles.length);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // Set the adapter for the list view
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_item,R.id.content, mPlanetTitles));
        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
        
        mDrawerToggle = new ActionBarDrawerToggle(this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description */
                R.string.drawer_close  /* "close drawer" description */) {

            
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) { getActionBar().setTitle(title); }
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) { getActionBar().setTitle("Open Drawer"); } }; // Set the drawer toggle as the DrawerListener mDrawerLayout.setDrawerListener(mDrawerToggle); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { selectItem(position); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Pass the event to ActionBarDrawerToggle, if it returns // true, then it has handled the app icon touch event if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // Handle your other action bar items... switch (item.getItemId()) { case R.id.action_settings: Toast.makeText(this, "Settings selected", Toast.LENGTH_LONG).show(); break; default: break; } return super.onOptionsItemSelected(item); }
/** Swaps fragments in the main content view */
private void selectItem(int position) { // create a new fragment and specify the planet to show based on position Fragment fragment = new OpertingSystemFragment(); Bundle args = new Bundle(); args.putInt(OpertingSystemFragment.ARG_OS, position); fragment.setArguments(args); // Insert the fragment by replacing any existing fragment FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.content_frame, fragment) .commit(); // Highlight the selected item, update the title, and close the drawer mDrawerList.setItemChecked(position, true); getActionBar().setTitle((mPlanetTitles[position])); mDrawerLayout.closeDrawer(mDrawerList); } }

This activity uses a navigation drawer icon based on the recommendations of Google. You find an icon set from Google under the following URL: Navigation Drawer Icons.

This should be sufficient to add the navigation drawer to your application.

Tip

The usage of the navigation drawer is currently very popular for Android application. It seem that this navigation pattern is well accepted by end users.

8.3. Tab navigation

Fragments can also be used in combination with the action bar for navigation. For this your main activity needs to implement a TabListener, which is responsible for moving between the tabs.

To add a new tab to the action bar, use the newTab() method.

The following code shows such an activity. It uses dummy activities to demonstrate the switch.

package com.vogella.android.actionbar.tabs;

import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener {

  
/** * The serialization (saved instance state) Bundle key representing the * current tab position. */
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set up the action bar to show tabs. final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // for each of the sections in the app, add a tab to the action bar. actionBar.addTab(actionBar.newTab().setText(R.string.title_section1) .setTabListener(this)); actionBar.addTab(actionBar.newTab().setText(R.string.title_section2) .setTabListener(this)); actionBar.addTab(actionBar.newTab().setText(R.string.title_section3) .setTabListener(this)); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { // Restore the previously serialized current tab position. if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) { getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM)); } } @Override public void onSaveInstanceState(Bundle outState) { // Serialize the current tab position. outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar() .getSelectedNavigationIndex()); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, show the tab contents in the // container view. Fragment fragment = new DummySectionFragment(); Bundle args = new Bundle(); args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, tab.getPosition() + 1); fragment.setArguments(args); getFragmentManager().beginTransaction() .replace(R.id.container, fragment).commit(); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { }
/** * A dummy fragment representing a section of the app */
public static class DummySectionFragment extends Fragment { public static final String ARG_SECTION_NUMBER = "placeholder_text"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TextView textView = new TextView(getActivity()); textView.setGravity(Gravity.CENTER); textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER))); return textView; } } }

8.4. Dropdown menu navigation

You can also use a spinner in the action bar. The following code demonstrates such an implementation.

package com.vogella.android.actionbar.spinner;

import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements
    ActionBar.OnNavigationListener {

  
/** * The serialization (saved instance state) Bundle key representing the * current dropdown position. */
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set up the action bar to show a dropdown list. final ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); final String[] dropdownValues = getResources().getStringArray(R.array.dropdown); // Specify a SpinnerAdapter to populate the dropdown list. ArrayAdapter<String> adapter = new ArrayAdapter<String>(actionBar.getThemedContext(), android.R.layout.simple_spinner_item, android.R.id.text1, dropdownValues); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Set up the dropdown list navigation in the action bar. actionBar.setListNavigationCallbacks(adapter, this); // use getActionBar().getThemedContext() to ensure // that the text color is always appropriate for the action bar // background rather than the activity background. } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { // Restore the previously serialized current dropdown position. if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) { getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM)); } } @Override public void onSaveInstanceState(Bundle outState) { // Serialize the current dropdown position. outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar() .getSelectedNavigationIndex()); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override public boolean onNavigationItemSelected(int position, long id) { // When the given dropdown item is selected, show its contents in the // container view. Fragment fragment = new DummySectionFragment(); Bundle args = new Bundle(); args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1); fragment.setArguments(args); getFragmentManager().beginTransaction() .replace(R.id.container, fragment).commit(); return true; }
/** * A dummy fragment */
public static class DummySectionFragment extends Fragment { public static final String ARG_SECTION_NUMBER = "placeholder_text"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TextView textView = new TextView(getActivity()); textView.setGravity(Gravity.CENTER); textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER))); return textView; } } }

8.5. Evaluation

While the navigation drawer is relatively new compared to the other options, it is pretty popular among users and Android applications. If in doubt which options to select, consider using the navigation drawer.

9. Exercise: ActionBar

9.1. Project

This chapter will demonstrate how to create actions in the action bar and react to the selection of the user.

It is based on the fragment tutorial which can be found under Android fragments tutorial. If you have already created this project, you can continue to reuse it. If not, the following describes the required setup to continue with this tutorial.

10. Exercise: Add an action bar to your application

10.1. Create an icon for the ActionBar

Continue to use the com.example.android.rssfeed project.

Use File → New → Other... → Android → Android Icon Set to create a refresh icon for your action bar. The wizard allows you to select which type of icons you want to create. Specify the name ic_refresh for the new icon and select a corresponding entry from the clipart.

Note

The Android design page also provides prepared icons for the ActionBar. You find the downloads on the following webpage.

http://developer.android.com/design/downloads/index.html 

If you choose to download and use these icons, select a fitting for a refresh action and place it into the /res/drawable-mdpi folder. Make sure that the filename of your icon isic_action_refresh

Warning

Icon filenames are not allowed to contain special character, cannot start with a number and must be in lower case.

10.2. Add a menu XML resource

Create a new XML resource called mainmenu.xml for your menu.

To create this XML file, select your project, right click on it and select File → New → Other... → Android → Android XML File.

Select the Menu option, enter mainmenu.xml as the filename and press the Finish button.

Creating a new XML resource for the menu

This creates a new menu file in the res/menu folder of your project.

10.3. Add actions to your menu resource

Open the mainmenu.xml file and select the Layout tab of the Android editor.

Press the Add button and select the Item entry.

Select Add in the Android menu editor

Select to add an item in the Android menu editor

Enter an entry similar to the following screenshot.

How to maintain the menu entries in an menu xml file

Add a second action to your menu. Use Refresh as the title attribute and action_refresh as the ID attribute.

Add a second entry to the menu with the ID attribute set to @+id/action_settings and the Title attribute set toSetting. Set the android:showAsAction to never.

10.4. Assign icons

Use the XML editor to assign the @drawable/ic_action_refresh to the action_refresh action via its android:iconproperty. You created or downloaded this icon in Section 10.1, “Create an icon for the ActionBar”.

Tip

It is suggested to add this icon to the action via the XML editor as the structured editor used to create invalid XML if you add it here directly. Potentially this bug is already fixed if you read this text.

10.5. Validate XML resource

The resulting XML should look similar to the following listing.

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_refresh"
        android:orderInCategory="100"
        android:showAsAction="always"
        android:icon="@drawable/ic_action_refresh"
        android:title="Refresh"/>
    <item
        android:id="@+id/action_settings"
        android:title="Settings"
        android:showAsAction="never"
        >
    </item>

</menu> 

10.6. Add the action bar to your activity

Change your RssfeedActivity class to the following code to use the new menu resource file.

package com.example.android.rssfeed;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class RssfeedActivity extends Activity implements
    MyListFragment.OnItemSelectedListener {
  // Unchanged
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rssfeed);
  }
  
  //NEW
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);
    return true;
  }
  
  //NEW
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_refresh:
      Toast.makeText(this, "Action refresh selected", Toast.LENGTH_SHORT)
          .show();
      break;
    case R.id.action_settings:
      Toast.makeText(this, "Action Settings selected", Toast.LENGTH_SHORT)
          .show();
      break;

    default:
      break;
    }

    return true;
  }

  // Other methods which this class implements
} 

10.7. Run the application and test the action bar

Run your application and validate that you can select both of your actions. Ensure that the correct info message is displayed if you select the different entries.

Social App running

Tip

If your device or emulator has an Option menu button, you will not see the overflow menu. Press the Option key to see your second action.

10.8. Remove the refresh button

If you have a refresh button in your fragment layout, you can remove it, as the action is used for the refresh operation.

11. Exercise: Using the contextual action mode

Create a project called de.vogella.android.socialapp with an activity called OverviewActivity.

Add an EditText element to your main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/myView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

</LinearLayout> 

Create a new menu XML resource with the contextual.xml file name.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/toast"
        android:title="Toast">
    </item>

</menu> 

Change your activity based on the default template to the following example.

package de.vogella.android.socialapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class OverviewActivity extends Activity {
  protected Object mActionMode;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // define the contextual action mode
    View view = findViewById(R.id.myView);
    view.setOnLongClickListener(new View.OnLongClickListener() {
      // called when the user long-clicks on someView
      public boolean onLongClick(View view) {
        if (mActionMode != null) {
          return false;
        }

        // start the CAB using the ActionMode.Callback defined above
        mActionMode = OverviewActivity.this
            .startActionMode(mActionModeCallback);
        view.setSelected(true);
        return true;
      }
    });
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    Toast.makeText(this, "Just a test", Toast.LENGTH_SHORT).show();
    return true;
  }

  private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

    // Called when the action mode is created; startActionMode() was called
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
      // inflate a menu resource providing context menu items
      MenuInflater inflater = mode.getMenuInflater();
      // assumes that you have "contexual.xml" menu resources
      inflater.inflate(R.menu.contextual, menu);
      return true;
    }

    // called each time the action mode is shown. Always called after
    // onCreateActionMode, but
    // may be called multiple times if the mode is invalidated.
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
      return false; // Return false if nothing is done
    }

    // called when the user selects a contextual menu item
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
      switch (item.getItemId()) {
      case R.id.toast:
        Toast.makeText(OverviewActivity.this, "Selected menu",
            Toast.LENGTH_LONG).show();
        mode.finish(); // Action picked, so close the CAB
        return true;
      default:
        return false;
      }
    }

    // called when the user exits the action mode
    public void onDestroyActionMode(ActionMode mode) {
      mActionMode = null;
    }
  };

} 

If you run this example and long press the EditText view, your contextual action bar is displayed.

Contextual ActionBar demonstrated


'Android > GUI & Activity' 카테고리의 다른 글

앱 최신버전 체크하는 방법  (0) 2014.11.19
Animation 종류  (0) 2014.10.28
AutoScaleTextView 추천 소스  (0) 2014.10.16
AutoScale TextView (4.4버전 테스트완료)  (0) 2014.10.15
CustomView lifeCycle  (0) 2014.09.30

https://github.com/grantland/android-autofittextview

출처 : http://ankri.de/autoscale-textview/

I was in need of a TextView that has a fixed with but dynamic content, so I needed the content to automatically scale.

The AutoScaleTextView takes the android:textSize value and uses it as the preferred text size. You can also set the minimum text size. The default for the minimum text size is 10dp. TheAutoScaleTextView now tries to take the maximum value between the preferred and minimum size that fits into the Views width (with regarding the padding).

Here is the result:

The AutoScale TextView in action displaying the android version names

You can see that the AutoScaleTextView automatically scales the text to fit in the Views width. For the different views I used layout_width: 130dp and layout_height=30dptextSize: 16dp and 10dp for the minTextSize. On the second Ice Cream Sandwich TextView I used 13dp for the minTextSizeand layout_height: wrap_content.

Get the source and explanation after the break.

The code itself is pretty simple. I improved a snippet I found on stackoverflow.com. I sadly cannot remember the exact post.

You can checkout the demo project: https://bitbucket.org/ankri/autoscaletextview/src

Or download the project: https://bitbucket.org/ankri/autoscaletextview/downloads

Please feel free to leave feedback or report bugs here:https://bitbucket.org/ankri/autoscaletextview/issues?status=new&status=open

Or view the code below:

The important part is the refitText(String, int) method. Note: If you are dealing with big textsizes you should set the treshold to a higher value.

Here is a snippet from the main.xml I used in the demo project

The values from the res/values/dimens.xml are 100dp for the width and 30dp for the height.

The content of the res/values/attrs.xml to alter the minTextSize in the layout files is:

 

And the content of the res/values/styles.xml to set the default minTextSize or other default styles for the AutoScaleTextView

 

Have fun using the code. I uploaded the code under the Beerware License. You can take the code and do whatever you want with it, as long as you mention me somewhere in your code, or your final app. If we ever meet and you think that the code, or explanation was helpful, feel free to buy me a beer and have a chat.

Or you could help a fellow out by donating some money.

Updated licence

When I uploaded this code I never thought anyone would use it, but since some people actually are using it, I updated the licence to Apache 2.0. But still… If you’re in the mood to buy me a beer. Please do :)

'Android > GUI & Activity' 카테고리의 다른 글

Animation 종류  (0) 2014.10.28
[펌[] Android ActionBar 활용  (0) 2014.10.22
AutoScaleTextView 추천 소스  (0) 2014.10.16
CustomView lifeCycle  (0) 2014.09.30
리스트뷰 밑의 내용 스크롤시 애니메이션 붙이는 방법  (0) 2014.09.25

리스트뷰 밑의 내용 스크롤시 애니메이션 붙이는 방법


https://github.com/cuub/sugared-list-animations

https://github.com/nhaarman/ListViewAnimations

오픈소스 사용하시면 됩니다.

'Android > GUI & Activity' 카테고리의 다른 글

Animation 종류  (0) 2014.10.28
[펌[] Android ActionBar 활용  (0) 2014.10.22
AutoScaleTextView 추천 소스  (0) 2014.10.16
AutoScale TextView (4.4버전 테스트완료)  (0) 2014.10.15
CustomView lifeCycle  (0) 2014.09.30

+ Recent posts