2013年12月6日金曜日

Android アプリをWebで公開

Android アプリを公開しようと、Webにアップしたが、ダウンロードに失敗することがある。

Biasic認証をかけているのだが、ググると、標準のブラウザでは、ダウンロードに認証情報が渡されないので、エラーになることが判明。

ChromeやFireFoxを使えば問題なし。


2013年8月13日火曜日

EditTextでEnterが押されたらキーボードを閉じる

 nname = (EditText)findViewById(R.id.nname);
 nname.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

                //EnterKeyが押されたかを判定
        if (event.getAction() == KeyEvent.ACTION_DOWN
        && keyCode == KeyEvent.KEYCODE_ENTER) {

                 //ソフトキーボードを閉じる
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
            //その後の処理をここに書くこともできる。
        return true;
        }
        return false;
        }
        });

2013年5月22日水曜日

WebViewの背景を透明にする

いろんな情報が錯そうしているが、以下の2つで解決

webview.setBackgroundColor(0) ; //(Color.TRANSPARENT);でもOK

loadUrlの前でも問題ない。

そして、マニフェストのandroid:hardwareAccelerated="false"が必要


    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:hardwareAccelerated="false" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:hardwareAccelerated="false" >

WebViewでフラッシュを表示するときは、android:hardwareAccelerated="true"が必要なので、背景は透明にできないようだ。

ちなみに、Android 3.2での結果。


2013年5月9日木曜日

Google Map v2


Google Map が v2 になってとても簡単になっていた。
また、サポートされなくなるので、変更しておいたほうがよい。

これを使うには、Google Play Services ライブラリをDLして、google-play-services_libフォルダをEclipceにImportし、
使用するプロジェクトでlibとしてリンクする必要がある。(Preferences-Android)

(例)
package com.example.mapv2text;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.support.v4.app.FragmentActivity;

public class MainActivity  extends FragmentActivity {

private GoogleMap mMap;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    @Override
    protected void onResume() {
        super.onResume();    
   // Do a null check to confirm that we have not already instantiated the map.
   if (mMap == null) {
       // Try to obtain the map from the SupportMapFragment.
       mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
               .getMap();
        mMap.setMyLocationEnabled(true); //My Locationボタンを表示する
       
        //Mapの中心とZoomを指定して表示
           //LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
           LatLng latLng = new LatLng(36.242612, 139.553061);
           CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 13);

        mMap.moveCamera(update);
         
       // マーカー表示
       if (mMap != null) {
        mMap.addMarker(new MarkerOptions()
        .position(new LatLng(36.242612, 139.553061))
        .title("タイトル")
        .snippet("ここはどこでしょう?")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon))
        );
         
       }
   }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

2013年5月7日火曜日

Google Map API Key 作成 

Google Maps API Android v2対応

コマンドプロンプトで実行

デバッグ時は、SDKに付属している、debug.keystoreを使用する。


C:\Users\_t>"c:\Program Files\Java\jre7\bin\keytool.exe" -list -v -keystore "c:\Users\_t\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

(リリース時のAPI Keyは、debug.keystoreを正規のkeystoreにする。)

以下のように表示される、SHA1を利用する。


証明書のフィンガプリント:
   MD5:  7C:57:DC:D6:01:1E:94:42:CD:CD:47:35:2B:97:66:A1
   SHA1: 97:54:EA:66:30:96:2F:54:7B:78:8A:6A:B0:AA:7E:0D:B4:53:CE:BC
   SHA256: 84:69:03:5A:B4:5E:1A:10:FE:60:35:5F:BE:1F:41:5C:AC:EA:2A:A4:8A:66:6A:1E:45:1A:98:02:46:D8:7B:2D
   署名アルゴリズム名: SHA256withRSA
   バージョン: 3

Google api console
https://code.google.com/apis/console/#project:147552444526

をブラウザで表示

Serviceで、Google Maps Android API v2をONにする
API Accesesで、SHA1と、セミコロン,パッケージ名を入れる。

97:54:EA:66:30:96:2F:54:7B:78:8A:6A:B0:AA:7E:0D:B4:53:CE:BC;com.example.mapdemo

Create New Android keyでAPI Keyを得る

はまった点:
APIキーを変更したときは、一度アプリを端末からアンインストールしないと、
有効にならず、地図が表示されなかった。







2013年4月30日火曜日

起動後、EditTextにフォーカスがあたってキーボードが出るのを防ぐ

起動後や、ダイアログ表示後に、いきなりキーボードが表示されるのを防ぐには、別のViewにフォーカスを映す。

例えば、TextViewにフォーカスを移してしまう。


    <TextView
   android:layout_width="300dp"
   android:layout_height="30dp"
   android:text="STB MAC Address"
   android:textSize="25dp"
   android:layout_margin="3dp"
        android:layout_marginLeft = "10dp"
        android:focusable="true" 
           android:focusableInTouchMode="true"  >
     <requestFocus /> 
     </TextView>

上の例のように

 android:focusable="true"
 android:focusableInTouchMode="true"
 <requestFocus />
の3行を入れる。


2013年4月10日水曜日

WindowsのSJISファイルを読む


    //Text File 読み込みメソッド

    public String readText(String filename) throws IOException{
        FileInputStream in = new FileInputStream(filename);
        BufferedReader reader = new BufferedReader(new InputStreamReader(in,"MS932"));
        StringBuffer sb = new StringBuffer();
        String sbs;
        while ((sbs = reader.readLine()) != null) {
            sb.append(sbs);
        }
        in.close();

        return sb.toString();
    }

InputStreamReaderに、MS932の指定が必要。これが無いと文字化けする。

WindowsのSJISは厳密にはSJISでなく、拡張されていて、MS932である。
Javaでは、Shift_JISはMS932のことらしい。

文字コード説明
ISO-8859-1ASCII。
ISO-2022-JPJISコード。
Shift_JISJDK1.1 までは SJIS と同義。JDK1.2 からは MS932 と同義。
SJISシフトJIS。
MS932Microsoft 932。シフトJISとほぼ同様だが若干異なる。
CP932Code Page 932。MS932 とほぼ同様だが若干異なる。
EUC_JPEUC。

2013年3月5日火曜日

ImageButtonを押したら背景色を変える


 View pushed = null;
//ボタン表示
private void cateBtn(ImageButton btn,int cate, String cateImg)
{
int id= getResources().
getIdentifier(cateImg, "drawable", getPackageName());  

btn.setLayoutParams(new LinearLayout.LayoutParams((int) (90.0*hw*0.9),(int) (114.0*hh*0.9)));
btn.setImageResource(id);
btn.setAdjustViewBounds(true);
btn.setPadding(0,0,0,0);
btn.setTag(cate);
layout.addView(btn);

//タッチされたら背景色を変える(前のボタンは戻す)
btn.setOnTouchListener(new View.OnTouchListener()
{
   public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
   if (pushed != null) pushed.setBackgroundColor(Color.GRAY); //戻す
   v.setBackgroundColor(Color.YELLOW);
}
if(event.getAction() == MotionEvent.ACTION_UP)
{
   //v.setBackgroundColor(Color.GRAY);
}
return false;
}
});

//ボタンが押されたとき
btn.setOnClickListener(new OnClickListener(){
   public void onClick(View view){
  if (pushed != null) pushed.setBackgroundColor(Color.GRAY); //戻す
  view.setBackgroundColor(Color.YELLOW);
  pushed = view;
   }
});
}

2013年2月21日木曜日

ListView(GridView)のOnItemClickが効かない

ListView(GridView)内に、ボタンを配置していると、リスト自体をタップしても、setOnItemClicklistenerが効かない。

対策:

ボタンに次の2行を追加する。

android:focusable="false"
android:focusableInTouchMode="false"



        <Button 
            android:id="@+id/cartBtn"
            android:layout_width="80dp"  
            android:layout_height="80dip" 
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:gravity="center"  
            android:background="@drawable/cart"
            android:focusable="false"
            android:focusableInTouchMode="false"
        />

2013年2月20日水曜日

Dialogを自動で閉じる



ダイアログでボタンを表示せず、数秒後に自動で閉じるインフォメーションを表示したいとき。

final AlertDialog.Builder dlg = new AlertDialog.Builder(Order.this);
dlg.setMessage("      注文を受け付けました");
dlg.setCancelable(true); //戻るキーで閉じる
final AlertDialog alt = dlg.create();

Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
     alt.dismiss();
}
};

alt.show();
handler.postDelayed(r, 2000); //2秒後に閉じる


popup menu


コンテキストメニューは大きすぎる。
リストビューで、各セル毎にメニューを出したいときはPopupMenuが便利

/res/menu/cart_menu.xml


<menu xmlns:android="http://schemas.android.com/apk/res/android">
    
    <item android:id="@+id/menu_del"
        android:title="削除する"
     />
    <item android:id="@+id/menu_up"
        android:title="1個増やす"
     />
    <item android:id="@+id/menu_down"
        android:title="1個減らす"
     />
</menu>

Java


//リストをクリックしたときの処理
listView.setOnItemClickListener(new OnItemClickListener(){    
public void onItemClick(AdapterView<?> parent, View view, 
int position,long id) {

    PopupMenu popup =new PopupMenu(Order.this, view);
popup.getMenuInflater().inflate(R.menu.cart_menu,   popup.getMenu());

popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

@Override
public boolean onMenuItemClick(MenuItem item) {
      switch(item.getItemId()){ case R.id.menu_del:      break; case R.id.menu_up:      break; case R.id.menu_down:      break; } return true;      }
});
 }
});



context menu

画面の真ん中に出るメニュー

/res/menu/cart_menu.xml


<menu xmlns:android="http://schemas.android.com/apk/res/android">
    
    <item android:id="@+id/menu_del"
        android:title="削除する"
     />
    <item android:id="@+id/menu_up"
        android:title="1個増やす"
     />
    <item android:id="@+id/menu_down"
        android:title="1個減らす"
     />
</menu>

java

ボタンなど、メニューを出すViewを設定

registerForContextMenu(listView);

//メニュー選択処理
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_del:
            // 全削除
            break;
        case R.id.menu_up:
            // 個数アップ
            break;
        case R.id.menu_down:
            // 個数ダウン
            break;
        default:
            return super.onContextItemSelected(item);
        }
        return true;
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
    ContextMenuInfo menuInfo){
    MenuInflater inf = getMenuInflater();
    inf.inflate(R.menu.cart_menu, menu);
    }


2013年2月15日金曜日

PopUp Window


popup.xml

<?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" 
    android:background="@color/LightSkyBlue">

<LinearLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
<ImageView
    android:id="@+id/popImg"
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:src="@drawable/dark"
    android:layout_margin="10dp"
    />
<LinearLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
<TextView
   android:id="@+id/popTitle"
   android:layout_width="500dp"
   android:layout_height="70dp"
   android:text="title"
   android:textSize="30dp"
   android:layout_margin="10dp"
   />
<TextView
   android:id="@+id/popDetail2"
   android:layout_width="400dp"
   android:layout_height="70dp"
   android:text="title"
   android:textSize="16dp"
   android:textColor="@color/red"
   android:layout_margin="10dp"
   />
<TextView
   android:id="@+id/popDetail1"
   android:layout_width="400dp"
   android:layout_height="140dp"
   android:text="title"
   android:textSize="16dp"
   android:layout_margin="10dp"
   />    
</LinearLayout>
</LinearLayout>
<LinearLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >
<Button
    android:id="@+id/btnPlay"
    android:layout_width="200dp"
    android:layout_height="50dp"
    android:layout_marginLeft="150dp"
    android:background="@drawable/btndmy"
    android:textColor="@android:color/white"
    android:textSize="30dp"
    android:text="PLAY" />

<Button
    android:id="@+id/btnCancel"
    android:layout_width="200dp"
    android:layout_height="50dp"
    android:layout_marginLeft="50dp"
    android:background="@drawable/btndmy"
    android:textColor="@android:color/white"
    android:textSize="30dp"
    android:text="Cancel" />
</LinearLayout>
</LinearLayout>

java


LayoutInflater layoutInf 
    = (LayoutInflater)getBaseContext()
     .getSystemService(LAYOUT_INFLATER_SERVICE);  
    View popupView = layoutInf.inflate(R.layout.popup, null);  
PopupWindow popupwindow = new PopupWindow(popupView);
popupwindow.setHeight(450);
popupwindow.setWidth(750);
popupwindow.showAtLocation(view, Gravity.CENTER, 0,0);
TextView title =(TextView)popupView.findViewById(R.id.popTitle);
TextView detail1 =(TextView)popupView.findViewById(R.id.popDetail1);
TextView detail2 =(TextView)popupView.findViewById(R.id.popDetail2);
title.setText(Title[id]);
detail1.setText(Detail1[id]);
detail2.setText(Detail2[id]);
ImageView img = (ImageView)popupView.findViewById(R.id.popImg);
int drawableID = getResources().
getIdentifier(ImageFile[id], "drawable", getPackageName());
img.setImageResource(drawableID);

//Cancel Button
Button btnCancel = (Button)popupView.findViewById(R.id.btnCancel);
    btnCancel.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
popupwindow.dismiss();
}});

//Play Button
Button btnPlay = (Button)popupView.findViewById(R.id.btnPlay);
btnPlay.setId(id);
    btnPlay.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
popupwindow.dismiss();
play(v.getId());
}});



2013年2月13日水曜日

GridViewで横スクロール

GridViewを使って横スクロールできる可変テーブルを作る
GridViewは縦にしか並ばないので、行数を2行に固定し、列数を可変にする。

java


adapter = new HereAdapter(this, R.layout.list, list);  
GridView listView = (GridView)findViewById(R.id.ListView);
listView.setAdapter(adapter);
//GridView を2行に固定するため列数を可変にする
listView.setNumColumns(list.size()/2); //Columns = Total/2
//幅=【セル幅220+spacing20 * Columns)
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(240*(list.size()/2),600);
listView.setLayoutParams(param);

main XML
横スクロールはHorizontalScroolViewを使用


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:padding="20dp">

    <HorizontalScrollView
        android:layout_width="1000dp"
        android:layout_height="match_parent"
         >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:orientation="horizontal"
            >

            <GridView
                android:id="@+id/ListView"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginLeft="0dp"
                android:background="@android:color/white"
                android:numColumns="1" 
                android:horizontalSpacing="20dp"
                android:verticalSpacing="20dp"
                android:layout_marginTop="10dp"
                android:padding="20dp">
            </GridView>
            

        </LinearLayout>
    </HorizontalScrollView>


list XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent" 
    android:layout_height="?android:attr/listPreferredItemHeight" 
    android:background="@color/gray" 
    android:padding="6dip">  
    
        
    <LinearLayout 
        android:orientation="vertical"  
        android:layout_width="0dip" 
        android:layout_weight="1"  
        android:layout_height="fill_parent"
        > 
         
        <ImageView 
            android:id="@+id/img" 
            android:layout_width="200dp"  
            android:layout_height="200dip" 
            android:layout_weight="1"
            android:gravity="center_vertical"  
            android:src="@drawable/ic_launcher"
            />
          
        <TextView 
            android:id="@+id/title"
            android:layout_width="fill_parent"  
            android:layout_height="50dip" 
            
            android:singleLine="true" 
            android:layout_weight="1"
            android:ellipsize="marquee" 
            android:textColor="@android:color/black"/>  

        
    </LinearLayout>  
</LinearLayout>