본문 바로가기

개발/모바일

CS 193A 16sp Lecture 07: Fragments

반응형

강의 링크 : https://www.youtube.com/watch?v=2DuvPuPR_c0&list=PLYKXDWkoIMUH088iBEr_B2WPfbPwtaG-V&index=7


1. 화면에 따라 다른 레이아웃/리소스 :  앱은 해당 suffix를 가진 폴더를 탐색한다. 

new layout > 같은 파일 이름 > Available qualifiers 에서 orientaton, screen size, screen density 등을 설정


 * screen density : (e.g. drawable-hdpi) xhdpi, hdpi, mdpi ...

 * screen size : (e.g. layout-large) small, normal, large

 * orientation : (e.g. layout-land) portrait(), land(landscape)

   - java 에서 orientation 확인하기

if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){}

or

(Stanford Library) isPortrait()



(Lec3의 닌자거북이 프로젝트에서 시작)


2. 사진을 누르면 디테일로


MainActivity 

 package com.example.han.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import stanford.androidlib.SimpleActivity;

public class MainActivity extends SimpleActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sherlockClick(View view){
ImageView img = (ImageView)findViewById(R.id.sherlockImage);
if(view.getId() == R.id.sherlock1Button){
img.setImageResource(R.drawable.sherlock1);
}else if(view.getId() == R.id.sherlock2Button){
img.setImageResource(R.drawable.sherlock2);
}else if(view.getId() == R.id.sherlock3Button){
img.setImageResource(R.drawable.sherlock3);
}
}
public void sherPicClick(View view){
Intent intent = new Intent(this, SherlockDetailActivity.class);
int num = 0;
if(findRadioButton(R.id.sherlock1Button).isChecked()) num = 0;
else if(findRadioButton(R.id.sherlock2Button).isChecked()) num = 1;
else if(findRadioButton(R.id.sherlock3Button).isChecked()) num = 2;

//extra parameters
intent.putExtra("num", num);
startActivity(intent);
}
}



activity_main.xml 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.han.fragment.MainActivity"
android:orientation="vertical">

<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center|top"
android:orientation="horizontal">
<RadioButton
android:id="@+id/sherlock1Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sherlock1"
android:onClick="sherlockClick"/>
<RadioButton
android:id="@+id/sherlock2Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sherlock2"
android:onClick="sherlockClick"/>

<RadioButton
android:id="@+id/sherlock3Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sherlock3"
android:onClick="sherlockClick"/>
</RadioGroup>
<ImageButton
android:id="@+id/sherlockImage"
android:src="@drawable/sherlock1"
android:onClick="sherPicClick"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout> 



 SherlockDetailActivity 

 package com.example.han.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import stanford.androidlib.SimpleActivity;

public class SherlockDetailActivity extends SimpleActivity {

private static final String[] SHERLOCK_INFO = {
"1. A Study in Pink\n" +
"88m\n" +
"A woman in pink is the fourth in a series of seemingly unrelated suicides, but Sherlock Holmes deduces that the deaths are actually murders most foul.",
"2. The Blind Banker\n" +
"88m\n" +
"Watson's new life with flatmate Sherlock Holmes is never dull, and even Sherlock's unusual idea of a visit to the bank keeps the doctor on his toes.",
"3. The Great Game\n" +
"89m\n" +
"Despairing of the ingenuity of London's criminals, Sherlock accepts what appears to be an ordinary case and discovers that a mastermind is at work."
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sherlock_detail);

// get parameter back
Intent intent = getIntent();
int num = intent.getIntExtra("num", 0);

// get TextView
TextView detailTextView = (TextView)findViewById(R.id.detailText);
detailTextView.setText(SHERLOCK_INFO[num]);
}
}


 activity_sherlock_detail

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.han.fragment.SherlockDetailActivity"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/detailText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>


</LinearLayout>



3. landscape모드에서는 사진과 디테일을 같이 보이기

fragment : 액티비티에서 나타날 수 있는 재사용가능한 안드로이드 UI의 조각

* 여러 디바이스나 화면 사이즈를 조작하는데 도움을 준다

* 여러 액티비티에서 공통된 부분을 재사용 할 수 있다.

* 안드로이드 3.0 이상에서만 사용 가능


* 프래그먼트 생성 : New > Fragment > Fragment(blank)

* 액티비티XML이 프래그먼트를 추가할 수 있다


* LifeCycle : OnCreateView(), OnActivityCreated()



- 프래그먼트 2개 추가 (체크박스 해제하면 자동으로 만들어지는 메소드를 없앨 수 있음)하고

XML코드 옮기기


fragment_sherlock_pic.xml 

 <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:orientation="vertical"
tools:context="com.example.han.fragment.SherlockPicFragment">


<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center|top"
android:orientation="horizontal">
<RadioButton
android:id="@+id/sherlock1Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sherlock1"
android:onClick="sherlockClick"/>
<RadioButton
android:id="@+id/sherlock2Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sherlock2"
android:onClick="sherlockClick"/>

<RadioButton
android:id="@+id/sherlock3Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sherlock3"
android:onClick="sherlockClick"/>
</RadioGroup>
<ImageButton
android:id="@+id/sherlockImage"
android:src="@drawable/sherlock1"
android:onClick="sherPicClick"
android:layout_width="match_parent"
android:layout_height="wrap_content" />


</LinearLayout>



fragment_sherlock_detail.xml  

 <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:orientation="vertical"
tools:context="com.example.han.fragment.SherlockDetailFragment">

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/detailText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>

</LinearLayout>




activity_main.xml

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.han.fragment.MainActivity"
android:orientation="vertical">

<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.example.han.fragment.SherlockPicFragment"
android:id="@+id/fragment1"
tools:layout="@layout/fragment_sherlock_pic"/>
<!--tools:layout="@layout/fragment_sherlock_pic" 프리뷰 끌어오기-->
</LinearLayout>



activity_sherlock_detail.xml 

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.han.fragment.SherlockDetailActivity"
android:orientation="vertical">
<fragment
android:id="@+id/fragment2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.example.han.fragment.SherlockDetailFragment"
tools:layout="@layout/fragment_sherlock_detail" />

</LinearLayout>




- 자바코드 (버튼 이벤트 핸들러 등) 옮기기

 

 SherlockPicFragment.java

 package com.example.han.fragment;


import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import stanford.androidlib.SimpleFragment;


/**
* A simple {@link Fragment} subclass.
*/
public class SherlockPicFragment extends SimpleFragment {

public SherlockPicFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sherlock_pic, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
sherlockClick(view);
}
};

getSimpleActivity().findRadioButton(R.id.sherlock1Button).setOnClickListener(listener);
getSimpleActivity().findRadioButton(R.id.sherlock2Button).setOnClickListener(listener);
getSimpleActivity().findRadioButton(R.id.sherlock3Button).setOnClickListener(listener);

getSimpleActivity().findImageButton(R.id.sherlockImage).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sherPicClick(view);
}
});
}

public void sherlockClick(View view){
// ImageView img = (ImageView)findViewById(R.id.sherlockImage);
ImageView img = (ImageView)getActivity().findViewById(R.id.sherlockImage);
if(view.getId() == R.id.sherlock1Button){
img.setImageResource(R.drawable.sherlock1);
}else if(view.getId() == R.id. sherlock2Button){
img.setImageResource(R.drawable.sherlock2);
}else if(view.getId() == R.id.sherlock3Button){
img.setImageResource(R.drawable.sherlock3);
}
}
public void sherPicClick(View view){
// Intent intent = new Intent(this, SherlockDetailActivity.class);
// this activity is the daddy activity of the activity that you're gonna launch
Intent intent = new Intent(getActivity(), SherlockDetailActivity.class);
int num = 0;
if(getSimpleActivity().findRadioButton(R.id.sherlock1Button).isChecked()) num = 0;
else if(getSimpleActivity().findRadioButton(R.id.sherlock2Button).isChecked()) num = 1;
else if(getSimpleActivity().findRadioButton(R.id.sherlock3Button).isChecked()) num = 2;

//extra parameters
intent.putExtra("num", num);
startActivity(intent);
}


}


 SherlockDetailFragment.java

 package com.example.han.fragment;



import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


/**
* A simple {@link Fragment} subclass.
*/
public class SherlockDetailFragment extends Fragment {
private static final String[] SHERLOCK_INFO = {
"1. A Study in Pink\n" +
"88m\n" +
"A woman in pink is the fourth in a series of seemingly unrelated suicides, but Sherlock Holmes deduces that the deaths are actually murders most foul.",
"2. The Blind Banker\n" +
"88m\n" +
"Watson's new life with flatmate Sherlock Holmes is never dull, and even Sherlock's unusual idea of a visit to the bank keeps the doctor on his toes.",
"3. The Great Game\n" +
"89m\n" +
"Despairing of the ingenuity of London's criminals, Sherlock accepts what appears to be an ordinary case and discovers that a mastermind is at work."
};

public SherlockDetailFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sherlock_detail, container, false);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// get parameter back
// Intent intent = getIntent();
Intent intent = getActivity().getIntent();
int num = intent.getIntExtra("num", 0);

// get TextView
TextView detailTextView = (TextView)getActivity().findViewById(R.id.detailText);
detailTextView.setText(SHERLOCK_INFO[num]);
}
}


-Landscape mode main activity 수정 (같은 액티비티 내에 존재하는 다른 프래그먼트를 업데이트 : Communication between fragments)


landscape모드의 xml파일도 프래그먼트로 바꿔주고 여기는 디테일도 추가

portrait모드에서는 버튼 클릭 시 detail 화면으로 넘어가는 것이지만, 여기서는 버튼 클릭 시 디테일 프래그먼트 부분의 텍스트가 바뀌도록 해줘야함


SherlockDetailFragment.java

 package com.example.han.fragment;



import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


/**
* A simple {@link Fragment} subclass.
*/
public class SherlockDetailFragment extends Fragment {
private static final String[] SHERLOCK_INFO = {
"1. A Study in Pink\n" +
"88m\n" +
"A woman in pink is the fourth in a series of seemingly unrelated suicides, but Sherlock Holmes deduces that the deaths are actually murders most foul.",
"2. The Blind Banker\n" +
"88m\n" +
"Watson's new life with flatmate Sherlock Holmes is never dull, and even Sherlock's unusual idea of a visit to the bank keeps the doctor on his toes.",
"3. The Great Game\n" +
"89m\n" +
"Despairing of the ingenuity of London's criminals, Sherlock accepts what appears to be an ordinary case and discovers that a mastermind is at work."
};

public SherlockDetailFragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sherlock_detail, container, false);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// get parameter back
// Intent intent = getIntent();
Intent intent = getActivity ().getIntent();
int num = intent.getIntExtra("num", 0);

setText(num);

}

public void setText(int num){
// get TextView
TextView detailTextView = (TextView)getActivity().findViewById(R.id.detailText);
detailTextView.setText(SHERLOCK_INFO[num]);
}
}


d

반응형