기술 블로그

[안드로이드 복습]프래그먼트 본문

Android

[안드로이드 복습]프래그먼트

jaegwan 2018. 11. 24. 22:44
반응형

매인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=".MainActivity"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/container">
<fragment
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="@+id/color_fragment"
android:name="com.example.tryfragment2.ColorFragment"
/>

</FrameLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="교체"
android:onClick="change"/>

</LinearLayout>



매인 액티비티

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
ColorFragment colorFragment = (ColorFragment) fragmentManager.findFragmentById(R.id.color_fragment);//연결

colorFragment.setColor(Color.GREEN);

}

public void change(View view) {
ColorFragment fragment =new ColorFragment();//교체버튼 클릭시 처리
int red = new Random().nextInt(256);//랜덤인수 설정
int blue = new Random().nextInt(256);
int green = new Random().nextInt(256);

getSupportFragmentManager().beginTransaction().replace(R.id.container,fragment).commit();
}
}



fragment_color.xml

<FrameLayout 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"
tools:context=".ColorFragment">

<!-- TODO: Update blank fragment layout -->
<TextView
android:id="@+id/hello_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />

</FrameLayout>



colorfragment.java

public class ColorFragment extends Fragment {
private TextView mHelloTextView;
private int mColor = Color.BLUE;


public ColorFragment() {//기본 빈 생성자 필수, 오버로드 금지 (번들만 가능)
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_color, container, false);
mHelloTextView= view.findViewById(R.id.hello_text);//textview연결
mHelloTextView.setBackgroundColor(mColor);

return view;
}

public void setColor(int Color){
mColor=Color;
if(mHelloTextView != null){
mHelloTextView.setBackgroundColor(mColor);
}




}

}


반응형
Comments