2015-10-29

[iOS] Auto Layout - NSLayoutConstraint

Object - C: 

NSMutableArray *myConstraints = [NSMutableArray array];
    
    NSDictionary *variableBindings = @{@"_btn_cancel" : _btn_cancel};
    NSDictionary *metrics = @{@"height": 100,
                              @"margin": 10};
    
   
    // ex1: 從水平方向佈局
    [myConstraints addObjectsFromArray:
     [NSLayoutConstraint constraintsWithVisualFormat:
                @"H:|-margin-[_btn_cancel(height)]-|"
                    options:NSLayoutFormatDirectionLeadingToTrailing
                    metrics:metrics
                     views:variableBindings]];
    
 //ex2: 從垂直方向佈局
 [myConstraints addObjectsFromArray:
    [NSLayoutConstraint constraintsWithVisualFormat:
        @"V:[ViewB(ViewA)]-|"
        options:NSLayoutFormatDirectionLeadingToTrailing
        metrics:nil
        views:NSDictionaryOfVariableBindings(ViewB,ViewA)]];
    


    [self.view addConstraints:myConstraints];



參數說明:

 options: 佈局時的順序,預設是由上而下(垂直)與由左而右(水平)

 metrics : 一般为nil ,参数类型为NSDictionary, 為要傳入的變數

views :
参数类型为NSDictionary, 為要傳入的Views



語法:


* " V: " 和 " H: "
分別代表由垂直或是水平方向來佈局。

*" | "
代表 Superview 的邊界。

*" - "
代表預設距離,例如在中間加上數字 " -20- ",則代表限制 20 個單位距離。

*" [ ] "
代表物件本身,括號內包含物件的變數名稱與大小限制,可以使用關係運算子(<=、>= 或 == 等)。

* " @ "
優先權,1 至 1000 的整數,優先權較大的條件會優先被滿足,例如 ,[ViewB(>=100@1000)],物件 ViewB 不可以小於 100 個單位長度或寬度會最優先被考慮。





2012-04-16

Intent呼叫第三方程式 (setComponent)

Intent呼叫第三方程式 (setComponent)


只要利用adb logcat ,再搭配使用setComponet(),就可以輕易的呼叫第三方程式(不在自己的application內)。
詳細用法參考原文:
http://developer.android.com/reference/android/content/Intent.html#setComponent%28android.content.ComponentName%29

比如我自己的程式想執行Android裡面的Settings,先用adb logcat看系統是如何呼叫Settings的

I/ActivityManager(   60): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.android.settings/.Settings }
I/ActivityManager(   60): Displayed activity com.android.settings/.Settings: 1205 ms (total 1205 ms)

只要有這個cmp就可以呼叫Settings了

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent i = new Intent();
        ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings");
        i.setComponent(comp);
        startActivity(i);   
    }
}

另外有些程式要被執行,Intent還要多加搭配Intent.setData()或者是Intent.setAction()等方式。比如:想要開啟Browser,而且是開啟tw.yahoo.com的網頁,程式碼如下:
        Intent i = new Intent();
        ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity");
        i.setComponent(comp);
        Uri uri = Uri.parse("http://tw.yahoo.com");
        i.setData(uri);
        startActivity(i);

出處
http://blog.xuite.net/ffc99a3b/ooxx/45834263-%5B%E8%BD%89%E8%BC%89%5D+Intent%E5%91%BC%E5%8F%AB%E7%AC%AC%E4%B8%89%E6%96%B9%E7%A8%8B%E5%BC%8F+(setComponent)+

2012-04-02

receiver


可以在代码文件中声明一个receiver,也可以在manifest中声明一个,前者中的receiver只有在该activity launch起来以后才会监听其所感兴趣的文件,而如果在androidManifext.xml中声明的话,就不受限制,随时可以监听感兴趣的事件。

首先谈谈在androidManifext.xml中注册一个receiver, 例如我们想监听相机按钮按下事件的发生,并且发生后调用我们的camera程序
  1. <receiver android:name="CameraButtonIntentReceiver">
  2.             <intent-filter>
  3.                 <action android:name="android.intent.action.CAMERA_BUTTON"/>
  4.             </intent-filter>
  5. </receiver>
复制代码
在这个配置文件中声明了一个receiver用来监听相机的按键事件,所以还需要在代码文件定义与配置文件中同名的receiver:
  1. public class CameraButtonIntentReceiver extends BroadcastReceiver {
  2. public void onReceive(Context context, Intent intent) {
  3.     Intent i = new Intent(Intent.ACTION_MAIN);
  4.         i.setClass(context, Camera.class);
  5.         i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  6.         context.startActivity(i);
  7. }
  8. }
复制代码

关于另外一种,在代码中注册一个receiver,例如我们想在代码文件中监听电池电量的变化,就可以按照如下方法
  1. private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
  2.       @Override
  3.         public void onReceive(Context context, Intent intent) {
  4.             String action = intent.getAction();
  5.               if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
  6.               …
  7.               }
  8.         }
  9. }
复制代码
这种方法需要在onCreate 或者onStart中注册该receiver所感兴趣的intent,如:
  1. registerReceiver(mBatteryReceiver, Intent.ACTION_BATTERY_CHANGED);
复制代码
在onStop及onDestroy中注销监听
  1. registerReceiver(mBatteryReceiver, Intent.ACTION_BATTERY_CHANGED);
复制代码

[Android] Incorporating Google AdMob Ads into your app

Incorporating Google AdMob Ads into your app is a three step process:
  1. Add the SDK JAR to your Eclipse project.
  2. Declare com.google.ads.AdActivity in AndroidManifest.xml.
  3. Set up required network permissions in the manifest.

Adding the SDK JAR

The decompressed SDK consists of a JAR, a javadoc folder and a README.
1. Right click on your app project in Eclipse and choose Properties.
2. Select Java Build Path and the Libraries tab. Then click Add External JARs... to add the Google AdMob Ads JAR.

com.google.ads.AdActivity

The AdMob Ads SDK requires that com.google.ads.AdActivity be declared in your app's AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
          package="com.company" 
          android:versionCode="1" android:versionName="1.0"> 
  <application android:icon="@drawable/icon" android:label="@string/app_name" 
               android:debuggable="true"> 
    <activity android:label="@string/app_name" android:name="BannerExample"> 
      <intent-filter> 
        <action android:name="android.intent.action.MAIN"/> 
        <category android:name="android.intent.category.LAUNCHER"/> 
      </intent-filter> 
    </activity> 
    <activity android:name="com.google.ads.AdActivity" 
              android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/> 
  </application> </manifest>

Permissions

Making ad requests requires the networking permissions INTERNET and ACCESS_NETWORK_STATE, so these must also be declared in the manifest:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
          package="com.company" 
          android:versionCode="1" android:versionName="1.0"> 
  <application android:icon="@drawable/icon" android:label="@string/app_name" 
               android:debuggable="true"> 
    <activity android:label="@string/app_name" android:name="BannerExample"> 
      <intent-filter> 
        <action android:name="android.intent.action.MAIN"/> 
        <category android:name="android.intent.category.LAUNCHER"/> 
      </intent-filter> 
    </activity> 
    <activity android:name="com.google.ads.AdActivity" 
              android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/> 
  </application> 
  <uses-permission android:name="android.permission.INTERNET"/> 
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> </manifest>
You should now be able to rebuild your project without any errors.

Adding a com.google.ads.AdView

Android apps are composed of View objects, Java instances the user sees as text areas, buttons and other controls. AdView is simply another View subclass displaying small HTML5 ads that respond to user touch.
Like any View, an AdView may be created either purely in code or largely in XML.
The five lines of code it takes to add a banner:
  • Import com.google.ads.*
  • Declare an AdView instance
  • Create it, specifying a unit ID—your AdMob publisher ID
  • Add the view to the UI
  • Load it with an ad
The easiest place to do all this is in your app’s Activity.
import com.google.ads.*; 
 public class BannerExample extends Activity { 
  private AdView adView; 
 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
 
    // Create the adView 
    adView = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID); 
 
    // Lookup your LinearLayout assuming it’s been given 
    // the attribute android:id="@+id/mainLayout" 
    LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout); 
 
    // Add the adView to it 
    layout.addView(adView); 
 
    // Initiate a generic request to load it with an ad 
    adView.loadAd(new AdRequest()); 
  } 
 
  @Override 
  public void onDestroy() { 
    if (adView != null) { 
      adView.destroy(); 
    } 
    super.onDestroy(); 
  } }
Warning: Make sure you're in test mode during development to avoid being disabled for clicking your own ads. See the Best Practices guide for more details on enabling test ads.
You can download an example project containing this code here and may alternately create your banner in XML.

The Result

When you now run your app you should see a banner at the top of the screen:

Note: The very first time AdMob sees your publisher ID it may take up to two minutes to receive an ad. This initial two minute lag will recur every time the ID goes unused for 24 hours.
Warning: All new Android apps created after October 14, 2011 will require an AdMob SDK that was released on or after March 15, 2011. This corresponds to version 4.0.2+ for Android. If you downloaded the library from our official download site, then you're already set. Otherwise you may have an old version of the AdMob SDK that was released prior to March 15, 2011, and your new app will not receive any ad impressions until you update your SDK.




source: