안드로이드 스튜디오 Fragment, AlertDialog, Snackbar 사용하기



Fragment란?

아래 사이트에 잘 나와있습니다.

- https://developer.android.com/guide/components/fragments.html?hl=ko#Design



public class Fragment1 extends Fragment {

@Nullable

@Override


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

this.inflater = inflater;

v = inflater.inflate(R.layout.fragment1, container, false );

return v;

}


Fragment를 extends 하고 Fragment에 붙일 layout을 작성하고 inflate를 해줍니다.


그리고 Fragment를 붙이고 싶은 Activity의 layout에 아래 코드를 추가합니다.


<fragment

    android:id="@+id/fragment"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:name="com.examples.androidpractice4_1.Fragment1"

/>


 name에는 들어가는 Activity에 들어가는 Fragment의 위치를 작성해줍니다.




AlertDialog는 안드로이드의 대화상자를 말합니다.


기본적인 형태의 AlertDialog는 Activity 코드 작성만을 통해 사용할 수 있습니다.

AlertDialog.Builder dialog = new AlertDialog.Builder(this);

dialog.setTitle("제목")
.setMessage("내용")
.setNegativeButton("닫기", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

}
})
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

}
})
.show();

setTitle은 제목 설정, setMessage는 내용설정 

setNegativeButton은 왼쪽에 있는 버튼

setPositiveButton은 오른쪽에 있는 버튼을 나타냅니다.

그리고 new OnClickListener 설정을 통해서 버튼 클릭 이벤트를 설정해 줄 수 있습니다.


AlertDialog의 모양을 원하는대로 바꾸고 싶다면 새로운 xml 파일을 만들고 .setView(int layoutResId)를 통해 붙여주면 됩니다.




Snackbar를 사용하기 위해서는 dependecy를 추가해야합니다.

File에서 ProjectStructure를 클릭해서 들어갑니다.


그리고 Dependencies를 클릭하고 + 버튼을 클릭합니다.


그리고 design을 입력하고 나오는 칸을 클릭하고 Ok를 누르면 Snackbar를 사용할 수 있습니다.


아래 앱은 Fragment, AlertDialog, Snackbar 사용해서 만든 앱입니다.


 

-

 

-

 


-


깃 허브 주소입니다.


https://github.com/Ywook/Android.practice4_1











+ Recent posts