728x90
반응형

커스텀 리스트뷰를 생성하는 방법입니다. 파이어베이스와 연동하였습니다.

 

리스트를 추가하고싶다면 따로 버튼을 만들어서 추가하시면 됩니다.

기본적인 코드와 동작을 확인하시면 좋을것같습니다.

 

리스트뷰 객체.java

//테이블이라고 생각하고, 테이블에 들어갈 속성값을 넣기
//파이어베이스는 RDBMS와 다르기 때문에 테이블이라는 개념이 없음. 원래는 키값이라고 부름
public class memo_list {
    String mname; //제목
    String mcontent; //내용

    public memo_list(){} // 생성자 메서드


    public String getmname() {
        return mname;
    }

    public void setmname(String mname) {
        this.mname = mname;
    }

    public String getmcontent() {
        return mcontent;
    }

    public void setmcontent(String mcontent) {
        this.mcontent = mcontent;
    }

    //값을 추가할때 쓰는 함수
    public memo_list(String mname, String mcontent){
        this.mname = mname;
        this.mcontent = mcontent;
    }
}

 

 

메인화면.java

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private ArrayList<memo_list> arrayList;
    private FirebaseDatabase database;
    private DatabaseReference databaseReference;

    //DatabaseReference는 데이터베이스의 특정 위치로 연결하는 거라고 생각하면 된다.
    //현재 연결은 데이터베이스에만 딱 연결해놓고 키값(테이블 또는 속성)의 위치 까지는 들어가지는 않은 모습이다.


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

        //커스텀 리스트뷰 시작
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true); // 리사이클러뷰 기존성능 강화
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        arrayList = new ArrayList<>(); // 그룹 객체를 담을 어레이 리스트 (어댑터쪽으로)

        database = FirebaseDatabase.getInstance(); // 파이어베이스 데이터베이스 연동
        databaseReference = database.getReference(); // DB 테이블 연결

        //값이 변경되는걸 감지하는 함수!
        databaseReference.child("memo").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                // 파이어베이스 데이터베이스의 데이터를 받아오는 곳
                arrayList.clear(); // 기존 배열리스트가 존재하지않게 초기화
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) { // 반복문으로 데이터 List를 추출해냄
                    memo_list memo_list = snapshot.getValue(memo_list.class); //객체를 선언하여 데이터를 담기
                    arrayList.add(memo_list); // 담은 데이터들을 배열리스트에 넣고 리사이클러뷰로 보낼 준비
                }
                adapter.notifyDataSetChanged(); // 리스트 저장 및 새로고침
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                // 디비를 가져오던중 에러 발생 시
                //Log.e("MainActivity", String.valueOf(databaseError.toException())); // 에러문 출력
            }


        });

        adapter = new memo_Adapter(arrayList, this);
        recyclerView.setAdapter(adapter); // 리사이클러뷰에 어댑터 연결

     }

}

 

 

어댑터.java

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

    private ArrayList<memo_list> arrayList;
    private Context context;
    private FirebaseDatabase database;
    private DatabaseReference databaseReference;

	//메인에서 어댑터로 받아온 값
    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) {
    	//메모 list.xml 연결하기
        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.mname.setText(arrayList.get(position).getmname());
        holder.mcontent.setText(arrayList.get(position).getmcontent());
        // 만약 정수형이라면 holder.gtime.setText(String.valueOf(arrayList.get(position).getstudytime()));


    }

    public class CustomViewHoler extends RecyclerView.ViewHolder {
    	//리스트.xml 요소 아이디 연결
        TextView mname;
        TextView mcontent;


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

        }
    }
}

 

 

 

리스트.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/gray"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_margin="10dp"
            android:layout_gravity="center"
            android:text="메모이름"
            android:textColor="@color/white"
            android:id="@+id/mname"
            android:textSize="20sp"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/white"
            android:visibility="invisible"
            android:id="@+id/mcontent"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:orientation="horizontal"
        android:background="@color/white"></LinearLayout>



</LinearLayout>

 

메인화면.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:background="@color/gray">

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


        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </androidx.recyclerview.widget.RecyclerView>



    </LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

: 편의를 위해 리니어 레이아웃 안에 감쌌습니다. androidx.coordinatorlayout속에 만든 이유는.. 제가 플로팅 버튼을 같이 사용하기 때문입니다. 애초에 리니어로 만드셔도 상관없습니다.

728x90
반응형
728x90
반응형

Activity에서 새로고침 하기

		finish();//인텐트 종료
                    overridePendingTransition(0, 0);//인텐트 효과 없애기
                    Intent intent = getIntent(); //인텐트
                    startActivity(intent); //액티비티 열기
                    overridePendingTransition(0, 0);//인텐트 효과 없애기

 

 

 

Adapter에서 새로고침 하기

			Intent intent = ((Activity)context).getIntent();
                        ((Activity)context).finish(); //현재 액티비티 종료 실시
                        ((Activity)context).overridePendingTransition(0, 0); //효과 없애기
                        ((Activity)context).startActivity(intent); //현재 액티비티 재실행 실시
                        ((Activity)context).overridePendingTransition(0, 0); //효과 없애기
728x90
반응형
728x90
반응형

포커싱과 터치가 안되도록 하는 부분만 넣어주면 됩니다.

 

저는 클릭이 안되는 것을 사용자에게 알리기 위해, 에딧텍스트에 회색 배경을 설정하였습니다.

Gname_edit.setBackgroundColor(ContextCompat.getColor(this,R.color.Gray));//배경색 설정
Gname_edit.setFocusable(false);//포커싱과
Gname_edit.setClickable(false);//터치가 안되도록!

 

728x90
반응형
728x90
반응형

플로팅 액션 버튼은 머터리얼 디자인 중 하나로, 화면 위에 위치가 고정된 버튼입니다.

 

스크롤 바를 내리든, 다른 일을 하든 설정된 위치에 고정되어있습니다. (해당 xml화면 안에서만)

 

 

 

 

머터리얼 디자인 사용 설정하기

Gradle Scripts -> build.gradle (Module: app) -> dependencides 안에 아래 코드를 입력합니다.

implementation 'com.google.android.material:material:1.1.0-beta01'

 

 

 

코드를 입력했다면, Sync Now를 눌러줍니다.

 

 

 

 

 

 

 

 

 

플로팅 버튼.xml

처음 xml을 만들었을때, 레이아웃을 androidx.coo 어쩌구로 설정해줍니다.

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:background="@color/White">

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

	//구현하고 싶은 화면은 이곳에 작성하시면 됩니다.


</LinearLayout>

//플로팅 버튼
<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/fab_btn"
    android:layout_gravity="end|bottom"
    android:layout_margin="16dp"
    app:fabSize="normal"
    app:elevation="6dp"
    app:backgroundTint="@color/Yellow"
    android:src="@drawable/ic_add_black_24dp"></com.google.android.material.floatingactionbutton.FloatingActionButton>


</androidx.coordinatorlayout.widget.CoordinatorLayout>

androidx.coordinatorlayout.widget.CoordinatorLayout 밑에 리니어 레이아웃을 하나 만들어서 그 안에 화면을 꾸미면 편합니다.

 

플로팅 버튼 선언은 coordinatorlayout 바로 아래에 들어가도록 하면 됩니다.

 

 

 

플로팅 버튼.class

public class Together_Customlist extends AppCompatActivity {

    FloatingActionButton fab;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.together_recycler);
        
        fab = (FloatingActionButton)findViewById(R.id.fab_btn);

      
        //플로팅 버튼
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(getApplicationContext(), make_group.class); //그룹 만들기 화면으로 연결
                startActivity(intent); //액티비티 열기
            }
        });

    }
}

플로팅 버튼을 누르면 새로운 액티비티가 열리도록 하였다.

728x90
반응형
728x90
반응형

작업할 클래스.java

public class make_group extends AppCompatActivity {

    Button add;
    CalendarView calendarView;


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

        add = (Button)findViewById(R.id.addGroup_btn);
        calendarView = (CalendarView)findViewById(R.id.calendarView);//캘린더뷰


        
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
	        //현재의 날짜와 시간을 가지고 있는 캘린더 객체 생성
                Calendar calendar = Calendar.getInstance();

                //캘린더뷰에서 날짜값 읽어오기
                Date date = new Date(calendarView.getDate());

                //캘린더 객체에 캘린더뷰 값을 넣음
                calendar.setTime(date);

                //캘린더뷰 값을 넣은 캘린더 객체의 날짜값을 문자열로 변환!
                // ex)2021-03-14
                String caldate = Integer.toString(calendar.get(Calendar.YEAR))+ "-" + Integer.toString(calendar.get(Calendar.MONTH)) + "-" +Integer.toString(calendar.get(Calendar.DATE));
                
            }
        });
    }
  
}

저는 버튼을 누르면 문자열에 캘린더뷰 날짜가 저장되도록 만들었습니다.

 

저는 사실 파이어베이스에 저장하도록 만들었었는데, 여러분도 그런식으로 활용하거나 텍스트뷰에 넣는 등 원하는대로 사용하시면 좋을것같습니다.

728x90
반응형
728x90
반응형

 

Glook_Adapter.java

package com.example.together.Group;

//import 부분은 지저분해서 지웠습니다.
//import android.widget.PopupMenu; 등 몇가지를 추가했던것 같은데..
//빨간줄 생기면 alt+enter로 추가하세요!


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


    private ArrayList<User_group> arrayList;
    private Context context;

    public Glook_Adapter(ArrayList<User_group> 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.glook_list, parent, false);
        CustomViewHoler holer = new CustomViewHoler(view);
        return holer;

    }

    @Override
    public void onBindViewHolder(@NonNull final CustomViewHoler holder, int position) {
        Glide.with(holder.itemView)
                .load(arrayList.get(position).getiv_people())
                .into(holder.iv_people); */
        holder.uname.setText(arrayList.get(position).getuname());

	//커스텀 리스트뷰의 리스트 자체를 가져옴.
        holder.itemView.setTag(position);
        //롱클릭 시
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
            	
                //여기서부터 팝업메뉴!
                PopupMenu popup= new PopupMenu(context.getApplicationContext(), view);//v는 클릭된 뷰를 의미

                popup.getMenuInflater().inflate(R.menu.user_menu, popup.getMenu());
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()){
                            case R.id.m1:
                                Toast.makeText(view.getContext(), "그룹장위임",Toast.LENGTH_SHORT).show(); //토스트로 실험
                                break;
                            case R.id.m2:
                                Toast.makeText(view.getContext(), "추방",Toast.LENGTH_SHORT).show(); //토스트로 실험
                                break;
                            default:
                                break;
                        }
                        return false;
                    }
                });
                popup.show();
                //여기까지 팝업메뉴!

                return true;
            }
        });



    }


    @Override
    public int getItemCount() {
        return (arrayList != null ? arrayList.size() : 0);
    }


    public class CustomViewHoler extends RecyclerView.ViewHolder {
        TextView uname;


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

        }
    }

}

public void onBindViewHolder 안에서 CustomViewHoler에서 선언한 itemView를 롱 클릭했을때, 팝업 메뉴가 나오도록 한다.

728x90
반응형
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