안드로이드/프로그래밍

[안드로이드]메모장 어플 개발 #3 [Intent 및 Dialog, ClickListener]

RBWSN 2015. 3. 2. 07:35
728x90
일단 오늘은 먼저 리스트뷰에 어떻게 클릭리스너를 연결하는지 알아보도록 한다.

클릭리스너에도 많은 방법이 있겠지만 나는 인터페이스를 받아와 사용하는법으로 쓸께 더많은 방법도 많으니 편한 방법을 쓰면 된다.

일단 먼저 인터페이스를 받아오기위해서는 메인에서 선언을 해줘야하는데
public class MemoMenu extends Activity implements OnItemClickListener , OnItemLongClickListener

이런식으로 상속을 받은뒤 


1
2
3
 
        listView.setOnItemClickListener(this); // 클릭리스너 연결
        listView.setOnItemLongClickListener(this); // 롱클릭리스너 연결
cs

원하는 리스트뷰에 연결을 시켜주면돼

그리고 나서는 오버라이드 받아 정의를 해줘야하는데

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view,
            int position, long id) { // 롱클릭 리스너
        // TODO Auto-generated method stub
        
        GetSet getSet = (GetSet) parent.getItemAtPosition(position);
        String title = getSet.getName();
        String memo = getSet.getMemo();
        String day = getSet.getDay();
        
        
        Log.i("Longclick""ok" + title + memo);
        
        return false;
    }
 
 
 
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) { // 클릭리스너
        // TODO Auto-generated method stub
        GetSet getSet = (GetSet) parent.getItemAtPosition(position);
        String title = getSet.getName();
        String memo = getSet.getMemo();
        String day = getSet.getDay();
        
        
        Log.i("click""ok" + title + memo);
        
    }
cs
이런식으로 연결을 하여 여기서 하고싶은 작업을 하면된다.


이게 잘동작하는 지 실험을 해보자.


 log로 클릭할때의 동작을 위에처럼 적용했는데 아이템을 클릭할때 잘 동작하는걸 알아볼수가 있다.


이제 인텐트를 알아보도록 하자 인텐트에서 자신의 값을 보낼때는 하나의 값을 따로 보내도 되지만
보통은 번들에 데이터를 넣어서 한꺼번에 보낸다.

코드는 이렇게 짜였는데 나는 db로 정보를 받아올것이므로 Id의 값만 받아왔다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) { // 클릭리스너
        // TODO Auto-generated method stub
        GetSet getSet = (GetSet) parent.getItemAtPosition(position); // 현재 아이템의 정보를 얻어옴
    
        /*Bundle bundle = new Bundle(); // 번들생성
        bundle.putString("title", getSet.getName()); // 번들에 스트링 타이틀값 넣기
        bundle.putString("memo", getSet.getMemo()); // 메모
        bundle.putString("day", getSet.getDay());  // 날짜
        bundle.putString("img", getSet.getImageName()); // 이미지 주소
        Intent intent = new Intent(MemoMenu.this, MemoVIew.class); // 인텐트 생성
        intent.putExtras(bundle); // 번들값 넣기*/
        
        int id2 = getSet.getId();
        Log.i("click""ok" + id2);
 
        Intent intent = new Intent(MemoMenu.this, MemoVIew.class); // 인텐트 생성
        intent.putExtra("Id", id2);
        
        
        
        startActivity(intent); // 인텐트 시작
    }
cs

그리고 클릭리스너 가 실행 된뒤의 액티비티는 이정보들을 볼수있는 뷰로써 레이아웃은 이렇게 정의했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.memoproz.MemoVIew" >
 
    <TextView
        android:id="@+id/ViewTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Large Text"
        android:singleLine="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <ImageView
        android:id="@+id/ViewImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ViewTitle"
        android:layout_centerHorizontal="true"
        android:adjustViewBounds="true"
        android:maxHeight="100sp"
        android:maxWidth="100sp"
        android:scaleType="fitCenter"
        android:padding="3sp"
        android:src="@drawable/ic_launcher" />
 
    <TextView
        android:id="@+id/ViewDay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/ViewImg"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceSmall" />
    <ScrollView 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/ViewDay">
        <TextView
                android:id="@+id/ViewMemo"
                android:layout_width="match_parent"
               android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                />
    </ScrollView>
    
 
</RelativeLayout>
 
cs



그리고 이제는 코드안에서 이 레이아웃의 텍스트뷰및 이미지와 연동을 시켜 자료를 넣어야한다.

나는 db로 받아왔는데 번들로 했더라도 String  값들이나 int 값들로 받아오면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package com.example.memoproz;
 
import android.app.Activity;
import android.content.*;
import android.database.*;
import android.database.sqlite.*;
import android.graphics.*;
import android.os.Bundle;
import android.util.*;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;
 
public class MemoVIew extends Activity {
    SQLiteDatabase db;
    Intent intent;
    
    public String DB_NAME = "MemoAPP.db"// 디비이름
    public String TABLE_NAME = "MemoTABLE"// 테이블 이름
    
    TextView ViewTitle;
    TextView ViewMemo;
    TextView ViewDay;    
    ImageView ViewImg;
    
    
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.memo_view);
        
        ViewMemo = (TextView)findViewById(R.id.ViewMemo);
        ViewTitle = (TextView)findViewById(R.id.ViewTitle);
        ViewDay = (TextView)findViewById(R.id.ViewDay);
        ViewImg = (ImageView)findViewById(R.id.ViewImg);
        
        db = openOrCreateDatabase(DB_NAME,MODE_WORLD_WRITEABLE,null); // 디비연결
        intent = getIntent(); // 인텐트를 받아와서 연결
 
        viewDB();
    }
    
    
    private void viewDB(){
        String sql;
        int getId = intent.getIntExtra("Id"0); // putIntIntent 정수 값으로 인텐트의 Id로 정의된 숫자값을 받아옴 
        //String str = intent.getStringExtra("title"); putStringIntent 스트링값으로 title이름으로 정의된  스트링 의 값을 받아옴
 
        sql = "select * from " + TABLE_NAME + " where _id =" + "'" + getId + "'"// 아이디로 디비의 정보를 받아옴
        
        Cursor cursor = db.rawQuery(sql, null);
        
        if(cursor !=null){
            int count  = cursor.getCount();
            String countI = String.valueOf(count);
            Log.i("count", countI);
            for(int i=0; i<count; i++){
                cursor.moveToNext();
                int id = cursor.getInt(0);
                String name  = cursor.getString(1);
                String memo = cursor.getString(2);
                String day = cursor.getString(3);
                String image = cursor.getString(4);
                
                
                ViewTitle.setText(name);
                ViewMemo.setText(memo);
                ViewDay.setText(day);
                ViewImg.setImageBitmap(BitmapFactory.decodeFile(image));
                
                
                
                Log.i("mPath""id : " + id);
 
                
                
            }
            
        }
        
    }
    
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.memo_view, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
 
cs
실행화면 이렇다.

이미지가 있을시///


이미지가 없을시///\



롱클릭 리스너에는 다이얼 박스만 넣어놨는데

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 
@Override
    public boolean onItemLongClick(final AdapterView<?> parent, View view,
            final int position, long id) { // 롱클릭 리스너
        // TODO Auto-generated method stub
        AlertDialog.Builder builder = new AlertDialog.Builder(this); // 액티비티 받아옴
        builder.setTitle("이미지 선택"// 다이얼박스 제목
        .setItems(items, new DialogInterface.OnClickListener() { // 아이템 클릭리스너
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                switch(which){
                case 0// 보기 호출
                    GetSet getSet = (GetSet) parent.getItemAtPosition(position); // 현재 아이템의 정보를 얻어옴
                    
                    /*Bundle bundle = new Bundle(); // 번들생성
                    bundle.putString("title", getSet.getName()); // 번들에 스트링 타이틀값 넣기
                    bundle.putString("memo", getSet.getMemo()); // 메모
                    bundle.putString("day", getSet.getDay());  // 날짜
                    bundle.putString("img", getSet.getImageName()); // 이미지 주소
                    Intent intent = new Intent(MemoMenu.this, MemoVIew.class); // 인텐트 생성
                    intent.putExtras(bundle); // 번들값 넣기*/
                    
                    int id2 = getSet.getId();
                    Log.i("click""ok" + id2);
 
                    Intent intent = new Intent(MemoMenu.this, MemoVIew.class); // 인텐트 생성
                    intent.putExtra("Id", id2);
                    
                    
                    
                    startActivity(intent); // 인텐트 시작
                    
                    break;
                case 1// 수정 호출
                    break;
                    
                case 2// 메모 공유 호출
                    break
                    
                    
                }
                
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
        
        
        return false;
    }
cs
롱클릭에서의 boolean 값은 롱클릭후 화면제어가 넘어가냐 안넘어가냐인데 초기에는 false 로 설정되어있지만 
롱클릭후의 이벤트를 계속 진행을 하고싶다면 false로 놔두고 끝내고 싶다면 true로 설정을 해놓으면된다.


 다음시간에는 수정하는 법과 옵션 메뉴를 사용하는 법을 알아보도록 하겠다.

728x90