MainActiviy
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_test, ItemFragment.newInstance(5));
fragmentTransaction.commit();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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.damoa.testfragment.MainActivity">
<LinearLayout
android:id="@+id/fragment_test"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
/>
</RelativeLayout>
ItemFragment
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ItemFragment extends Fragment {
private static final String ARG_COLUMN_COUNT = "column-count";
private int mColumnCount = 0; //액티비티 와 프레그먼트 데이터 전달 예제
/**
* 액티비티 -> 프래그먼트 데이터 전달 예제
* @param columnCount
* @return
*/
public static ItemFragment newInstance(int columnCount) {
ItemFragment fragment = new ItemFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 액티비티 -> 프래그먼트 데이터 전달 예제
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list, container, false);
return view;
}
}
'Android' 카테고리의 다른 글
안드로이드 액티비티 애니메이션 (0) | 2016.11.14 |
---|---|
RecyclerView 만들기 (0) | 2016.11.14 |
Toolbar 안에 SearchView 넣고 RecycleView filter로 실시간 검색 (7) | 2016.11.08 |
android SHA1 알아내기 (0) | 2016.10.19 |
Android TextView Line 가져오기 (0) | 2016.09.21 |