이 블로그 검색

2011년 11월 16일 수요일

해당 객체의 클래쓰 이름을 가져올 때

객체의 getClass() 의 getName()을 사용하면 팩키지 이름을 포함한 클래쓰 이름을 가져온다.

Ex)
if(this.getClass().getName().equals("com.lge.readersworld.view.DiscoverDetailListLandView"))
{
           .................................
           .................................
}

2011년 11월 15일 화요일

동적으로 화면 전환 고정시키기

어떤 특정 상황에서만 화면을 고정시켜야 될 때가 있다.
그럴 때는

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);   // 세로 고정
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 가로 고정
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);  // 다시 원래 대로

를 사용하자.

Ex)


if(bottomLayout.getVisibility() == View.VISIBLE){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

bottomLayout 이 보일때는 화면 세로로 고정...



@Override
public void onBackPressed() {
selectedBubbleNum = -1;
if(bottomLayout.getVisibility() == View.VISIBLE){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}else{
finish();
}
}



Back 키를 누루면 다시 자유자재로 변환

2011년 11월 14일 월요일

안드로이드 HardKey 사용

로그 캣을 보면 하드키를 누를 때, 아래와 같이 해당 하드키에 대한 KeyCode 값이 나오는 걸 알 수 있다.

================

11-15 13:13:21.859: INFO/WindowManager(201): [e] [interceptKeyTq] event.scancode139
11-15 13:13:21.859: DEBUG/WindowManager(201): keyEvent event=KeyEvent{action=0 code=82 repeat=0 meta=0 scancode=0 chars=null mFlags=0}
11-15 13:13:21.867: INFO/InputMethodService(293): [T] Scancode = 139,  Keycode = 82
11-15 13:13:21.882: INFO/WindowManager(201): [e] [interceptKeyTq] event.scancode139
11-15 13:13:21.882: DEBUG/WindowManager(201): keyEvent event=KeyEvent{action=1 code=82 repeat=0 meta=0 scancode=0 chars=null mFlags=0}


=================

아래와 같이 onKeyDown() 메서드를 이용해 키 클릭에 대한 이벤트를 잡아 올 수 있다.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == 82){
                      /* 이부분에 구현할 Action 을 넣는다.   */
Intent intent = new Intent(this, DiscoverSearchActivity.class);
intent.putExtra("cpName", app_id);
intent.putExtra("package_nm", package_nm);
Util.startActivity(this, intent);
                   /* Action */
}
return super.onKeyDown(keyCode, event);
}


2011년 11월 9일 수요일

안드로이드 서버 통신 API

public String getData(String url, Map<String, String> headers, Map<String, String>[] params, boolean isPostType) throws Exception {

StringBuilder sb = new StringBuilder();
InputStream is = null;
DefaultHttpClient httpclient = null;
BufferedReader reader = null;
try {
httpclient = new DefaultHttpClient();

HttpParams httpParams = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, HTTP_TIMEOUT);

HttpResponse response = null;

if (params != null && isPostType) {     // Post 방식 일때
HttpPost httpPost = new HttpPost(url);
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    for (int i=0;i<params.length;i++) {
for (Map.Entry<String, String> entry: params[i].entrySet()) {
        nameValuePairs.add(new BasicNameValuePair(entry.getKey(), (String)entry.getValue()));
        Util.log("param :: "+ entry.getKey() +"="+entry.getValue());
}
    }
    UrlEncodedFormEntity entityRequest = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
    httpPost.setEntity(entityRequest);
    if (headers != null) {
       for (Map.Entry<String, String> entry2: headers.entrySet()) {
        httpPost.addHeader(entry2.getKey(), entry2.getValue());
        Util.log("header :: "+entry2.getKey()+"="+ entry2.getValue());
       }
}
    response httpclient.execute(httpPost);


//DefaultHttpClient 객체의 execute 함수의 파라메터에 httpRequest 객체    (httpPost, httpGet)를 넘겨주면 HttpResponse 객체를 리턴

} else {                                                          //Get 방식일때
if (params != null) {
if (params[0].entrySet().size() > 0) url += "?";
for (Map.Entry<String, ?> entry : params[0].entrySet()) {
if (entry.getValue() instanceof String[]) {
String[] values = (String[]) entry.getValue();
for (int i = 0; i < values.length; i++) {
url += entry.getKey() + "=" + values[i] + "&";
}
} else {
url += entry.getKey() + "=" + entry.getValue() + "&";
}
}
}

       HttpGet httpget = new HttpGet(url);
       Util.log("network", "url = "+url);
if (headers != null) {
       for (Map.Entry<String, String> entry2: headers.entrySet()) {
        httpget.addHeader(entry2.getKey(), entry2.getValue());
       }
}
response = httpclient.execute(httpget);
}

is = response.getEntity().getContent();

reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);

String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}

} catch (Exception e) {
Util.logError(e);
throw e;
} finally {
try {
if (is != null) is.close();
if (reader != null) reader.close();

} catch (Exception e) {throw e;}
}

xmlValue = sb.toString();
Log.d("debug", "url = " + url);
Log.d("debug", xmlValue);
return xmlValue;
}

Intent Action을 통한 다른 Application 끼리 통신.

http://alnova2.tistory.com/365   <-- 요기서 퍼옴.

setAction(key) 와 intent-filter 의 action tag 로 통신 할 수 있음. 


* 인텐트 Sender & Receiver  <-- Application 1
1. intentsender.java
package com.android.intentsender;
....
public class intentsender extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // sendIntent
        Intent i = new Intent();
        i.setAction("com.android.intentsender.sendintent");   <-- setAction 으로 Action Key 값을 날린다.
        i.putExtra("send", "Hello I'am Intent sender");
        startActivityForResult(i,1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        TextView tv=(TextView)findViewById(R.id.tv01);
        if(resultCode==RESULT_OK){
            if (requestCode==1){
                tv.setText(data.getStringExtra("reply"));
            }
        }
    }
}
2. layout/main.xml
<?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"
    >
<TextView  
    android:id ="@+id/tv01"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>

- 이 어플리케이션은 com.android.intentsender.sendintent(임의의) 라는 action 을 가지고 activity를 실행한다. 실행한 결과를 TextView에 뿌리도록 한다

* 인텐트 Receiver/Reply   <-- application 2
1. intentreceiver.java
package com.android.intentreceiver;
....
public class intentreceiver extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent i = getIntent();
        TextView tv=(TextView)findViewById(R.id.tv01);
        tv.setText(i.getStringExtra("sender"));
        i.putExtra("reply","Hello I'am IntentReceiver");
        setResult(RESULT_OK,i);
        finish();
    }
}
- 이 어플리케이션은 intent를 받아서 reply를 설정하고 종료한다.

* 인텐트 sender/receiver를 호출하면 화면 맨 위에 인텐트 Receiver/Reply 어플리케이션에서 받은 문자열을 출력하는 것을 알수 있다. 그런데 인텐트 Receiver/Reply 어플리케이션에서 해당 인텐트를 받기 위해서는  intentreceiver의 AndroidManifest.xml에 다음과 같이 intent-filter설정을 해주어야 한다
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.android.intentreceiver"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".intentreceiver"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="com.android.intentsender.sendintent" />   <-날린 Action Key로 받는다. 
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="3" />
</manifest> 

2011년 11월 7일 월요일

텍스트 컬러에 셀렉터를 넣는 법

아래와 같이 글씨에도 셀렉터를 줄 수 있다.
텍스트컬러 속성에 파일을 연동시키고, 일반 셀렉터 파일을 쓰는 것과 같은 원리로 쓰면 된다.

  <TextView android:id="@+id/item_title"
      android:layout_width="match_parent"
      android:textSize="17.5dp"
       android:textColor="@color/discover_category_title" 
      android:gravity="center_horizontal"
      android:textStyle="bold"
      android:paddingTop="3dp"
      android:layout_height="wrap_content"
               android:layout_below="@id/item_icon"/>  


discover_category_title.xml


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

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

<item android:state_selected="true" android:color="@color/white" />

<item android:state_pressed="true" android:color="@color/white" />

<item android:state_focused="true" android:color="@color/white" />

<item android:color="@color/black" />

</selector>

스크롤 뷰 막기

아래와 같이 onScrollChanged 를 오버라이딩 한다.

@Override      //스크롤 막음
public void onScrollChanged(int x, int y, int x2, int y2){
Util.log(" x-position = " + x + " this.getWidth() = " + this.getWidth() );
if(x < this.getWidth()){
scrollTo(0, 0);
return;
}
}

가로뷰였는데, 그래서 x좌표가 this.getWidth() 즉 해당 뷰의 가로 크기보다 작을 때, 
바로 scrollTo(0,0) 로 박아주었더니 가로 스크롤이 안 움직임. 
세로 뷰 같은 경우는 y와 getHeight()를 쓰면 될 듯.

또 한가지 방법. 
onTouchEvent()를 이용 - 특정 조건에 해당하면 바로 return 한다.


public boolean onTouchEvent(MotionEvent ev) {      // 데이타가 없는 경우 스크롤 안되게 고정.
if (WishListActivity.wishListDataArr.get(0).getTitle().equals(""))  // 데이터가 없을 조건 
                   return false;
else 
                   return super.onTouchEvent(ev);
}