Fragment에서, add나 Replace를 한 후, back버튼을 누르면, 이전 Fragment를 복원해 줄 수 있다.
바로, addToBackStack() 메소드를 이용한다.
샘플 코드는 다음과 같다.
1. FragmentExample04Activity.java
package fragment.example04;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
public class FragmentExample04Activity extends Activity {
private Button addFragmentBtn;
private int currentIdx = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addFragmentBtn = (Button) findViewById(R.id.add_fragment);
addFragmentBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_cont, new MyFragment(currentIdx));
ft.addToBackStack(null);
ft.commit();
currentIdx++;
}
});
}
}
2. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@+id/fragment_cont"
android:layout_weight="1"
android:layout_width="0dip"
android:layout_height="match_parent" />
<Button
android:id="@+id/add_fragment"
android:layout_weight="0"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Add Fragment" />
</LinearLayout>
3. MyFragment.java
package fragment.example04;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MyFragment extends Fragment {
private int currentCnt;
public MyFragment(int _currentCnt){
this.currentCnt = _currentCnt;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, null);
((TextView) view.findViewById(R.id.title)).setText(currentCnt + "번째 Fragment.!");
return view;
}
}
4. fragment.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/title"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello" />
</LinearLayout>
위코드를 작성해 주면 된다.
완성 화면은 다음과 같다.
우측의 Add Fragment를 누르면, Fragment가 더해지며,
하단의 <- 버튼을 눌러주게 되면, 이전의 Fragment가 복원된다.
'Programming > android/tablet' 카테고리의 다른 글
ActionBar에 메뉴 넣기. (0) | 2011.12.24 |
---|---|
Action Bar 숨기기 (3) | 2011.12.24 |
java코드를 이용하여, Fragment사용하기. (0) | 2011.12.04 |
xml을 이용해 Fragment이용하기. (9) | 2011.12.04 |
fragment란? (0) | 2011.12.04 |