728x90
반응형

번들을 사용하여 프래그먼트 간 데이터를 전달하는 간단한 예제입니다.

 

 

 

 

 

 


activity.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">

    <FrameLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>
</LinearLayout>

 

 

fragment_1.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"
    android:orientation="vertical">

    <EditText
        android:id="@+id/edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:hint="이름을 쓰세요"
        android:textSize="30sp"/>

    <Button
        android:id="@+id/btn"
        android:layout_width="100dp"
        android:layout_marginLeft="10dp"
        android:layout_height="wrap_content"
        android:text="확인" />
</LinearLayout>

 

 

fragment_2.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">

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:text="이름"
        android:textSize="30sp"/>

</LinearLayout>

 

 

 

 

 

 

 


 

MainActivity.java

public class MainActivity extends AppCompatActivity {

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


        //프래그먼트1 연결
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment1 fragment1 = new Fragment1();
        transaction.replace(R.id.frame, fragment1);
        transaction.commit();


    }
}

 

 

Fragment1.java

public class Fragment1 extends Fragment {

    private View view;
    private Button btn;
    EditText edit;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_1, container, false);

        edit = view.findViewById(R.id.edit);
        btn = view.findViewById(R.id.btn);


        btn.setOnClickListener(new View.OnClickListener() { // 프래그먼트2로 이동
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle(); // 번들을 통해 값 전달
                bundle.putString("name",edit.getText().toString());//번들에 넘길 값 저장
                FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
                Fragment2 fragment2 = new Fragment2();//프래그먼트2 선언
                fragment2.setArguments(bundle);//번들을 프래그먼트2로 보낼 준비
                transaction.replace(R.id.frame, fragment2);
                transaction.commit();
            }
        });


        return view;
    }


}

 

 

Fragment2.java

public class Fragment2 extends Fragment {

    private View view;
    private TextView tv_name;
    private String name;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_2, container, false);

        tv_name = view.findViewById(R.id.tv_name);

        if (getArguments() != null)
        {
            name = getArguments().getString("name"); // 프래그먼트1에서 받아온 값 넣기
            tv_name.setText(name);
        }


        return view;
    }


}

 

 

728x90
반응형
728x90
반응형

Adapter.java

public class memo_Adapter extends RecyclerView.Adapter<memo_Adapter.CustomViewHoler> {


    private ArrayList<memo_list> arrayList;
    private Context context;


    public memo_Adapter(ArrayList<memo_list> arrayList, Context context) {
        this.arrayList = arrayList;
        this.context = context;
    }

    @NonNull
    @Override
    public CustomViewHoler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.memo_list, parent, false);
        CustomViewHoler holder = new CustomViewHoler(view);

        return holder;
    }

   @Override
    public void onBindViewHolder(@NonNull final CustomViewHoler holder, int position) {

	holder.itemView.setTag(position); //커스텀 리스트 뷰의 각각의 리스트를 의미
        holder.mname.setText(arrayList.get(position).getmname());//


        //리스트 클릭 이벤트
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String mname = holder.mname.getText().toString(); //holder로 가져온 값을 변수에 넣기
       
                Intent intent;//인텐트 선언
                intent = new Intent(context, look_memo.class); //look_memo.class부분에 원하는 화면 연결
                intent.putExtra("mname", mname); //변수값 인텐트로 넘기기
                context.startActivity(intent); //액티비티 열기

            }
            
        });
    }
    
    @Override
    public int getItemCount() {
        return (arrayList != null ? arrayList.size() : 0);
    }
    
    
    
    public class CustomViewHoler extends RecyclerView.ViewHolder {
    
        TextView mname;


        public CustomViewHoler(@NonNull View itemView) {
            super(itemView);
            this.mname = itemView.findViewById(R.id.mname);

        }
    }

onBindViewHolder 부분에서 커스텀 리스트뷰를 눌렀을 경우 새로운 화면을 열도록 설정

 

 

 

 

 

 

Adapter에서 지정한 리스트를 눌렀을때 나오는 화면.java

public class look_memo extends AppCompatActivity {

    private Intent intent; //인텐트 선언
    String mname;
 

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

        intent = getIntent();// 인텐트 받아오기
        name = intent.getStringExtra("mname"); //Adapter에서 받은 키값 연결
   
    }
}

 

728x90
반응형
728x90
반응형

 

 

카톡이나 인스타그램 같은 앱을 보시면 하단에 탭 버튼이 있어, 각 탭을 눌러서 화면을 이동할 수 있도록 되어있습니다.

 

만약 옆으로 밀어서 화면이 넘어가는 탭을 만들고 싶다면 '뷰클리퍼'를 사용할 수 있습니다.

 

 

 

 

탭 호스트는 탭 버튼에 맞는 화면을 갈아끼울 수 있는 장소라고 생각하시면 됩니다.

 

각 버튼에 맞는 화면은 1개씩만 지정이 가능하고 사진을 연결할 수도 있고,

xml을 따로 연결할 수도 있어서 각 탭 버튼에 맞는 화면 구현이 가능합니다.

 

각 탭버튼마다 xml을 연결한다면, 필요한 xml의 개수는 4개 입니다.

 

탭 호스트 xml 1개, 각 화면에 맞는 xml 3개!

 

 

 

 

 

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

<TabHost
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@android:id/tabhost">

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@android:id/tabcontent">

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tab_study"
android:orientation="vertical" ></LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/tab_time"></LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/tab_group"></LinearLayout>

</FrameLayout>



<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"></TabWidget>


</LinearLayout>


</TabHost>

</LinearLayout>

프레임 레이아웃 안쪽 리니어 레이아웃이 3개가 있습니다.

이 리니어 레이아웃의 개수가 버튼의 개수라고 생각하시면 됩니다.

 

만약 탭 버튼들이 하단이 아니라 상단에 위치하는것을 원하신다면 탭위젯을 프레임레이아웃 바로 위로 올려주시면 됩니다.

 

 

 

 

 

 

 

MainActivity.java

package com.example.together;


import androidx.appcompat.app.AppCompatActivity;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;



@SuppressWarnings("deprecation") //이거 있어야 합니다.

public class MainActivity extends TabActivity {



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


TabHost tabHost = getTabHost(); //탭 호스트 객체 생성

// 탭스팩 선언하고, 탭의 내부 명칭, 탭에 출력될 글 작성
TabHost.TabSpec spec;
Intent intent; //객체




//탭에서 액티비티를 사용할 수 있도록 인텐트 생성
intent = new Intent().setClass(this, Study.class);
spec = tabHost.newTabSpec("Study"); // 객체를 생성
spec.setIndicator("공부하기"); //탭의 이름 설정
spec.setContent(intent);
tabHost.addTab(spec);



//탭에서 액티비티를 사용할 수 있도록 인텐트 생성
intent = new Intent().setClass(this, Time.class);
spec = tabHost.newTabSpec("Time"); // 객체를 생성
spec.setIndicator("통계"); //탭의 이름 설정
spec.setContent(intent);
tabHost.addTab(spec);



//탭에서 액티비티를 사용할 수 있도록 인텐트 생성
intent = new Intent().setClass(this, Together_home.class);
spec = tabHost.newTabSpec("Together_home"); // 객체를 생성
spec.setIndicator("그룹"); //탭의 이름 설정
spec.setContent(intent);
tabHost.addTab(spec);



tabHost.setCurrentTab(0); //먼저 열릴 탭을 선택! (2)로 해두면 그룹이 시작 화면!


}

}

각 탭에 맞는 xml이 연결될 수 있도록 자바코드를 작성해줍니다. xml에 맞는 java파일을 꼭 만드셔야해요.

 

intent = new Intent().setClass(this, Together_home.class); 이 부분이 각 탭에 맞는 화면이 나올 수 있도록 인텐트 하는 부분입니다.

 

 

 

 

Together_home.java

package com.example.together;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;



public class Together_home extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.together_home); //xml연결



}

}

그룹 버튼을 눌렀을떄 연결되는 자바파일 입니다. xml과 연결되어 있어야 합니다.

 

새로운 자바파일을 추가했으면, Manifest에 추가하는거 잊지 마시길 바랍니다.

 

 

 

 

 

 

 

결과 화면

 

728x90
반응형

+ Recent posts