반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형

3과에서는 날씨 리스트에서 한 라인을 클릭하면 그 날의 자세한 날씨가 표시되도록 할 겁니다.
클릭하면 다른 화면으로 넘어가는데요. 이것은 또 다른 Activity를 생성하고 Main Activity 에서 이 새로운 Activity로 전환할 수 있는 기능이 필요합니다.
그리고 새로운 화면 (Activity)로 넘어간 후 그곳에서 표시해 줄 정보를 출력해서 보여주는 UI를 만드는 일도 해야 하구요.

대충 이런 기능들을 구현할 것 같습니다.

리스트에서 아이템을 클릭했을 경우 작동하는 메소드는 setOnItemClickListener 입니다.
https://developer.android.com/reference/android/widget/ListView.html

이 메소드를 기존 코드에서 구현할 겁니다.

ForecastFragment class의 onCreateView 로 가서 맨 아래에 아래와 같이 코드를 추가합니다.



       // Get a reference to the ListView, and attach this adapter to it.
        ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
        listView.setAdapter(mForecastAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String forecast = mForecastAdapter.getItem(position);
                Toast.makeText(getActivity(), forecast, Toast.LENGTH_SHORT).show();
            }


listView.setAdapter(mForecastAdapter); 까지는 이전에 있었습니다.

그 이후에 setOnItemClickListener() 를 구현했는데요.

이 메소드 안의 onItemClick()을 Override 했습니다.


이 안에서는 클릭한 아이템의 포지션을 Toast로 보이도록 했습니다.



이렇게 하면 위에 보이는 것처럼 아이템을 클릭했을 시 그 아이템 내용이 Toast에 잠깐 보였다가 사라집니다.


이렇게 되면 onItemClick 까지 제대로 잘 작동 되고 있는 것을 알 수 있습니다.



이 다음에는 클릭한 날의 자세한 날씨를 보여주는 새로운 페이지로 이동해야 합니다.


그러려면 이동할 페이지를 만들어야 하고 이 새로운 페이지를 AndroidManifest파일에 등록해야 합니다.


이 새로운 페이지에서는 이전 화면으로 돌아가는 버튼을 만들겁니다.

그리고 그 아래에 해당 날짜의 자세한 정보를 보여 줄것이구요.


우선 DetailActivity를 생성합니다.


New-Activity-Blank Activity 를 선택합니다.



Activity 이름은 DetailActivity로 하고 Hierarchical Parent는 MainActivity로 합니다.

그리고 Use a Fragment도 선택을 합니다.



그러면 DetailActivity클래스와 함께 DetailActivityFragment 클래스가 자동으로 생성됩니다.

그리고 관련된 xml파일들도 생성됩니다. (activity_detail.xml, fragment_detail.xml)


일단 DetailActivity는 이렇게 만듭니다.



/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.sunshine.app;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

public class DetailActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.detail, 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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
            return rootView;
        }
    }
}


그리고 activity_detail.xml은 이렇게 합니다.


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container"
    android:layout_width="match_parent" android:layout_height="match_parent"
    tools:context="com.example.android.sunshine.app.DetailActivity" tools:ignore="MergeRootFrame" />


그리고 menu_detail.xml은 detail.xml로 이름을 바꿉니다.

해당 xml에서 오른쪽 마우스 클릭을 한 후 Refactor - Rename을 선택하면 이름을 바꿀 수 있습니다.



그리고 DetailActivityFragment.java는 delete합니다.

이건 현재 DetailActivity.java에 있는 PlaceholderFragment.java로 replace될 겁니다.


이렇게 된 코드는 3.02_create_detail_activity  에서 받아 볼 수 있습니다.





Activity들 간에 이동을 하려면 startActivity(Intent)를 사용하면 됩니다.


위에서 Toast를 구현했던 부분에 이 startActivity()를 구현할 겁니다.


setOnItemClick()을 아래와 같이 바꿉니다.


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String forecast = mForecastAdapter.getItem(position);
                //Toast.makeText(getActivity(), forecast, Toast.LENGTH_LONG).show();

Intent intent = new Intent(getActivity(), DetailActivity.class).putExtra(Intent.EXTRA_TEXT, forcast);

startActivity(intent)

            } 


이렇게 하면 DetailActivity 클래스로 이동합니다.


현재 상태에서는 DetailActivity로 넘어가면 아무것도 안 보일 겁니다.


fragment_detail.xml 에 있는 내용이 뿌려질건데 현재 그 내용은 아래와 같습니다.


<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.android.sunshine.app.DetailActivityFragment">


</RelativeLayout>


아무것도 내용이 없습니다.


여기에 해당 날짜의 forcast data를 읽어서 뿌려 주도록 하겠습니다.


DetailActivity의 onCreateView() 안에 아래와 같이 코등합니다.


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.fragment_detail, container, false);

            // The detail Activity called via intent.  Inspect the intent for forecast data.
            Intent intent = getActivity().getIntent();
            if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
                String forecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
                ((TextView) rootView.findViewById(R.id.detail_text))
                        .setText(forecastStr);
            }

            return rootView;
        }


그리고 fragment_detail.xml은 아래와 같이 합니다.


<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.android.sunshine.app.DetailActivity.DetailFragment">

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
        android:id="@+id/detail_text"
        android:layout_height="wrap_content" />

</RelativeLayout>


이제 리스트 아이템을 클릭하면 Toast가 나오는 대신 아래와 같이 DetailActivity가 표시 될 겁니다.




여기까지 진행된 소스코드는 이곳에서 받으실 수 있습니다.


https://github.com/udacity/Sunshine-Version-2/tree/3.04_populate_detail_text




이제 DetailActivity에 해당 날짜의 자세한 날씨를 표시하는 화면을 구성할 차례입니다.


이 작업은 다음 글에서 이어 나가겠습니다.




반응형
이전 1 다음