IT/Android

Fragment 전환

바바옄 2015. 6. 25. 17:29
반응형

MainActivity.java

 

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
package com.ktds.mychangefragment;
 
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
 
 
public class MainActivity extends ActionBarActivity {
 
    private Fragment fragment1;
    private Fragment fragment2;
    private Fragment fragment3;
 
    public Fragment getFragment1() {
        return fragment1;
    }
 
    public Fragment getFragment2() {
        return fragment2;
    }
 
    public Fragment getFragment3() {
        return fragment3;
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        fragment1 = new Fragment1(this);
        fragment2 = new Fragment2(this);
        fragment3 = new Fragment3(this);
 
 
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.container, getFragment1());
        transaction.commit();
    }
 
}
 
cs

 

 

 

activity_main.xml

 

1
2
3
4
5
6
7
8
9
10
<LinearLayout
    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:id="@+id/container"
    android:orientation="horizontal"
    tools:context=".MainActivity">
</LinearLayout>
 
cs

 

 

 

fragment_item.xml

 

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
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <ImageView
        android:id="@+id/poster"
        android:layout_width="100dp"
        android:layout_height="100dp"
        />
    <TextView
        android:id="@+id/subject"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/poster"
        android:text="제목"
        android:textSize="18dp"
        android:textStyle="bold"
        android:singleLine="true"
        android:layout_marginLeft="10dp"/>
 
    <TextView
        android:id="@+id/pubDate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="제작년도"
        android:textSize="16dp"
        android:layout_below="@+id/subject"
        android:layout_toRightOf="@+id/poster"
        android:layout_marginLeft="10dp"/>
 
    <TextView
        android:id="@+id/director"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="감독"
        android:textSize="16dp"
        android:layout_below="@+id/pubDate"
        android:layout_toRightOf="@+id/poster"
        android:layout_marginLeft="10dp"/>
 
    <TextView
        android:id="@+id/actors"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="출연배우"
        android:textSize="16dp"
        android:layout_below="@+id/director"
        android:layout_toRightOf="@+id/poster"
        android:layout_marginLeft="10dp"/>
 
    <RatingBar
        style="?android:attr/ratingBarStyleSmall"
        android:id="@+id/userRating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/actors"
        android:layout_toRightOf="@+id/poster"
        android:layout_marginLeft="10dp"/>
 
 
</RelativeLayout>
 
cs

 

 

 

Fragment1.java

 

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
package com.ktds.mychangefragment;
 
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
 
public class Fragment1 extends Fragment {
 
    private ListView listView;
    private Handler handler;
    private MovieItemAdapter adapter;
    private MainActivity context;
 
    public Handler getHandler() {
        return handler;
    }
 
    public MovieItemAdapter getAdapter() {
        return adapter;
    }
 
    public Fragment1(Context context) {
        this.context = (MainActivity) context;
    }
 
    private Button btnGoNext;
 
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
        View rootView = inflater.inflate(R.layout.fragment_1, container, false);
        context.setTitle("Fragment1");
 
        btnGoNext = (Button) rootView.findViewById(R.id.btnGoNext);
        btnGoNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentTransaction transaction = context.getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.container, context.getFragment2());
                // 뒤로 가기 눌렀을때 이전 FragMent를 보기 위해
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });
 
        adapter = new MovieItemAdapter(this);
        handler = new Handler();
        listView = (ListView) rootView.findViewById(R.id.listView);
        listView.setAdapter(adapter);
 
        new Thread(new RequestMovieInfoThread(this)).start();
 
        return rootView;
    }
}
 
cs

 

 

 

fragment_1.xml

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <!-- TODO: Update blank fragment layout -->
    <Button
        android:id="@+id/btnGoNext"
        android:text="Go Next"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
 
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
 
</LinearLayout>
 
cs

 

 

Fragment2.java

 

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
package com.ktds.mychangefragment;
 
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
 
public class Fragment2 extends Fragment {
 
    private  MainActivity context;
 
    public Fragment2(Context context) {
        this.context = (MainActivity) context;
    }
 
    private Button btnGoNext, btnGoMain;
 
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
        View rootView = inflater.inflate(R.layout.fragment_2,container,false);
 
        context.setTitle("fragment2");
 
        btnGoNext = (Button) rootView.findViewById(R.id.btnGoNext);
        btnGoNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentTransaction transaction = context.getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.container, context.getFragment3());
                // 뒤로 가기 눌렀을때 이전 FragMent를 보기 위해
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });
        btnGoMain = (Button) rootView.findViewById(R.id.btnGoMain);
        btnGoMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentTransaction transaction = context.getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.container, context.getFragment1());
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });
 
        return rootView;
    }
}
 
cs

 

 

 

fragment_2.xml

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <!-- TODO: Update blank fragment layout -->
    <Button
        android:id="@+id/btnGoNext"
        android:onClick="goNext"
        android:text="Go Next"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
 
    <Button
        android:id="@+id/btnGoMain"
        android:text="Go Main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
 
</LinearLayout>
 
cs

 

 

 

Fragment3.java

 

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
package com.ktds.mychangefragment;
 
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
 
 
public class Fragment3 extends Fragment {
 
    private MainActivity context;
 
    public Fragment3(Context context) {
        this.context = (MainActivity) context;
    }
 
    private Button btnGoMain;
 
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
        View rootView = inflater.inflate(R.layout.fragment_3, container, false);
 
        context.setTitle("Fragment3");
 
        btnGoMain = (Button) rootView.findViewById(R.id.btnGoMain);
        btnGoMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentTransaction transaction = context.getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.container, context.getFragment1());
                // 뒤로 가기 눌렀을때 이전 FragMent를 보기 위해
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });
        return rootView;
    }
}
 
cs

 

 

 

fragment_3.xml

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <Button
        android:id="@+id/btnGoMain"
        android:text="Go Main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
 
</LinearLayout>
cs

 

 

RequestMovieInfoThread.java

 

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
package com.ktds.mychangefragment;
 
import android.content.Context;
import android.support.v4.app.Fragment;
 
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
/**
 * Created by 206-001 on 2015-06-25.
 */
public class RequestMovieInfoThread implements Runnable {
 
    private Fragment fragment;
    private Context context;
 
    public RequestMovieInfoThread(Fragment fragment) {
        this.fragment = fragment;
        this.context = fragment.getActivity();
    }
 
    @Override
    public void run() {
 
        try {
            URL urlForHttp = new URL("http://openapi.naver.com/search?key=c1b406b32dbbbbeee5f2a36ddc14067f&query=벤허&display=10&start=1&target=movie ");
 
            // URL로 연결을 준비함.
            HttpURLConnection conn = (HttpURLConnection)urlForHttp.openConnection();
            conn.setConnectTimeout(1000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
 
            InputStream inputStream = null;
 
            // conn.getResponseCode() 호출 됬을 때 URL로 연결함
            if( conn.getResponseCode() == HttpURLConnection.HTTP_OK){
                // byte로 되있는 html tag 들
                inputStream = conn.getInputStream();
            }
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            Document document = builder.parse(inputStream);
            DocumentUtil.processDocument(document);
 
            //TODO 계속 작성해야 함
            ((Fragment1)fragment).getHandler().post(new Runnable() {
                @Override
                public void run() {
                    // 외부에서 데이터를 받아와서 listView를 갱신한다.
                    ((Fragment1)fragment).getAdapter().setMovieInfoList(DocumentUtil.getMovieInfoList());
                    ((Fragment1)fragment).getAdapter().notifyDataSetChanged();
                }
            });
 
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
 
    }
}
 
cs

 

 

MovieItemAdapter.java

 

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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package com.ktds.mychangefragment;
 
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
 
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
 
/**
 * Created by 206-001 on 2015-06-25.
 */
public class MovieItemAdapter extends BaseAdapter{
 
    private List<MovieInfo> movieInfoList;
    private Fragment fragment;
    private Context context;
 
    public void setMovieInfoList(List<MovieInfo> movieInfoList) {
        this.movieInfoList = movieInfoList;
    }
    public MovieItemAdapter(Fragment fragment) {
 
        this.fragment = fragment;
        this.context = fragment.getActivity();
        this.movieInfoList = new ArrayList<MovieInfo>();
    }
 
    @Override
    public int getCount() {
        return this.movieInfoList.size();
    }
 
    @Override
    public Object getItem(int position) {
        return this.movieInfoList.get(position);
    }
 
    @Override
    public long getItemId(int position) {
        return position;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
 
        MovieInfoHolder holder = null;
 
        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.fragment_item, parent, false);
 
            holder = new MovieInfoHolder();
            holder.poster = (ImageView) convertView.findViewById(R.id.poster);
            holder.subject = (TextView) convertView.findViewById(R.id.subject);
            holder.pubDate = (TextView) convertView.findViewById(R.id.pubDate);
            holder.director = (TextView) convertView.findViewById(R.id.director);
            holder.actors = (TextView) convertView.findViewById(R.id.actors);
            holder.userRating = (RatingBar) convertView.findViewById(R.id.userRating);
        }
        else{
            holder = (MovieInfoHolder) convertView.getTag();
        }
 
        MovieInfo movieInfo = (MovieInfo) getItem(position);
        holder.subject.setText(movieInfo.getSubject());
        holder.pubDate.setText(movieInfo.getPubDate());
        holder.director.setText(movieInfo.getDirector());
        holder.actors.setText(movieInfo.getActors());
        holder.userRating.setRating(movieInfo.getUserRating() / 2.0f);
 
        getBitmap(movieInfo.getImageUrl(), holder, context);
        convertView.setTag(holder);
 
        return convertView;
    }
 
    private class MovieInfoHolder{
 
        public ImageView poster;
        public TextView subject;
        public TextView pubDate;
        public TextView director;
        public TextView actors;
        public RatingBar userRating;
    }
 
    private void getBitmap(final String url, final MovieInfoHolder holder, Context context){
 
 
        // http 요청하기 위해 thread 필요
        new Thread(){
 
            @Override
            public void run() {
                if(url.length() > 0){
                    URL imgUrl = null;
                    HttpURLConnection connection = null;
 
                    try{
                        imgUrl = new URL(url);
                        connection = (HttpURLConnection) imgUrl.openConnection();
                        connection.setDoInput(true);
                        connection.connect();
 
                        final Bitmap bitmap = BitmapFactory.decodeStream(connection.getInputStream());
 
                        ((Fragment1)fragment).getHandler().post(new Runnable() {
                                    @Override
                                    public void run() {
                                        holder.poster.setImageBitmap(bitmap);
                                    }
                                });
 
                    }catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    finally {
                        if(connection != null){
                            connection.disconnect();
                        }
                    }
                }
            }
        }.start();
    }
}
 
cs

 

 

MovieInfo.java

 

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
package com.ktds.mychangefragment;
 
/**
 * Created by 206-001 on 2015-06-25.
 */
public class MovieInfo {
 
    private String imageUrl;
    private String subject;
    private String pubDate;
    private String director;
    private String actors;
    private float userRating;
 
    public String getImageUrl() {
        return imageUrl;
    }
 
    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }
 
    public String getSubject() {
        return subject;
    }
 
    public void setSubject(String subject) {
        this.subject = subject;
    }
 
    public String getPubDate() {
        return pubDate;
    }
 
    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }
 
    public String getDirector() {
        return director;
    }
 
    public void setDirector(String director) {
        this.director = director;
    }
 
    public String getActors() {
        return actors;
    }
 
    public void setActors(String actors) {
        this.actors = actors;
    }
 
    public float getUserRating() {
        return userRating;
    }
 
    public void setUserRating(float userRating) {
        this.userRating = userRating;
    }
}
 
cs

 

 

DocumentUtil.java

 

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
package com.ktds.mychangefragment;
 
import android.util.Log;
 
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * Created by 206-001 on 2015-06-25.
 */
public class DocumentUtil {
    private static List<MovieInfo> movieInfoList;
 
    public static List<MovieInfo> getMovieInfoList(){
        List<MovieInfo> tempList = new ArrayList<MovieInfo>();
 
        if(movieInfoList != null){
            tempList.addAll(movieInfoList);
        }
 
        return tempList;
    }
 
    public static void processDocument(Document document){
 
        // 초기화
        movieInfoList = new ArrayList<MovieInfo>();
 
        // XML을 얻어화서 변환한 Document 객체를 Element로 받아온다.
        // Element는 Document에 포함되는 객체를 말한다.
        // 이 Element는 여러개의 Node를 가진다.
 
        Element docElement = document.getDocumentElement();
 
        // item이라는 이름의 Element를 가져온다.
        // 이 Element는 여러개의 Node를 가지고 있다.
        NodeList nodeList = document.getElementsByTagName("item");
 
        MovieInfo movieInfo = null;
        if(nodeList != null && nodeList.getLength() >0){
            for(int i=0; i<nodeList.getLength(); i++){
 
                // 각각의 Item Node에서 Movie 정보를 가져온다.
                movieInfo = getConvertNodeToMovieInfo((Element)nodeList.item(i));
                if(movieInfo != null){
                    movieInfoList.add(movieInfo);
                }
            }
        }
 
    }
 
    private static MovieInfo getConvertNodeToMovieInfo(Element entry){
 
        MovieInfo movieInfo = null;
 
        try{
            // 데이터 꺼내오기
            Element image = (Element) entry.getElementsByTagName("image").item(0);
            Element subject = (Element) entry.getElementsByTagName("title").item(0);
            Element pubDate = (Element) entry.getElementsByTagName("pubDate").item(0);
            Element director = (Element) entry.getElementsByTagName("director").item(0);
            Element actors = (Element) entry.getElementsByTagName("actor").item(0);
            Element userRating = (Element) entry.getElementsByTagName("userRating").item(0);
 
            // 데이터 채우기
            movieInfo = new MovieInfo();
            movieInfo.setImageUrl( getValue(image) );
            movieInfo.setSubject( getValue(subject) );
            movieInfo.setPubDate( getValue(pubDate) );
            movieInfo.setDirector( getValue(director) );
            movieInfo.setActors( getValue(actors) );
            movieInfo.setUserRating(Float.parseFloat( getValue(userRating) ));
 
        }catch (DOMException dome){
            // throw new ~~ 이거 안드로이드에서는 절대 하지마
            // 로그 사용해라.
            dome.printStackTrace();
            Log.d("ERROR", dome.getMessage());
        }
 
        return movieInfo;
    }
 
    private static String getValue(Element element){
 
        String value = "";
 
        if(element != null && element.getFirstChild() != null){
            value = element.getFirstChild().getNodeValue();
        }
        return value;
    }
}
 
cs

 

 

 

 

     

 

 

 

반응형

'IT > Android' 카테고리의 다른 글

Android Studio에 Sliding Menu 설정 및 적용하기  (2) 2015.06.30
안드로이드 특강  (0) 2015.06.29
Fragment Data 전달  (0) 2015.06.25
View Pager  (0) 2015.06.25
Networking - API 요청하기  (0) 2015.06.24