Android_Fragment 실습

홍성채·2022년 4월 30일
0

Android

목록 보기
27/27

실습하기




MainActivity

package com.example.ex0430;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;

public class MainActivity extends AppCompatActivity {
    BottomNavigationView bottomNav;
    Fragment1 frag_home;
    Fragment2 frag_time;
    Fragment3 frag_option;

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

        bottomNav = findViewById(R.id.bottomNav);

        frag_home = new Fragment1();
        frag_time = new Fragment2();
        frag_option = new Fragment3();

        //실행 시 처음 보여줄 프래그먼트 화면 설정
        //replace(프래그먼트를 보여주는 레이아웃 리소스 ID, 보여줄 프래그먼트객체)
        getSupportFragmentManager().beginTransaction().replace(R.id.container, frag_home).commit();
        //메뉴버튼 클릭 시 화면 전환
        bottomNav.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                //선택한 메뉴버튼에 대한 리소스ID 저장
                int itemId = item.getItemId();
                if(itemId == R.id.home){
                    getSupportFragmentManager().beginTransaction().replace(R.id.container, frag_home).commit();
                }else if(itemId == R.id.timer){
                    getSupportFragmentManager().beginTransaction().replace(R.id.container, frag_time).commit();
                }else{
                    getSupportFragmentManager().beginTransaction().replace(R.id.container, frag_option).commit();
                }
                return false;
            }
        });
    }
}

activity_main

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.9" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNav"
        android:layout_width="410dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline2"
        app:menu="@menu/menu_item" />

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/home"
        android:icon="@android:drawable/ic_menu_myplaces"
        android:title="" />
    <item
        android:id="@+id/timer"
        android:icon="@android:drawable/ic_menu_agenda"
        android:title="타이머" />
    <item
        android:id="@+id/option"
        android:icon="@android:drawable/ic_lock_silent_mode"
        android:title="설정" />
</menu>

Fragment1.class

package com.example.ex0430;

import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class Fragment1 extends Fragment {
    WebView webView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_1, container, false);
        webView = view.findViewById(R.id.webView);

        //SharedPreferences에 저장된 데이터 접근
        String url = getActivity().
                getSharedPreferences("mySPF", Context.MODE_PRIVATE).
                getString("url","https://www.smhrd.or.kr");


        // 안드로이드에 설치되어 있는 기본 브라우저 실행
        // --> WebSettings 객체를 이용해서 Webview에 바로 띄워지도록 설정
        WebSettings settings = webView.getSettings();

        //자바스크립트 사용 허용
        settings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl(url );
        return view;
    }
}

fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<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=".Fragment1">

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

fragment2

package com.example.ex0430;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2 extends Fragment {

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

fragment2.xml

<?xml version="1.0" encoding="utf-8"?>
<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=".Fragment2">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="두번째화면" />

</FrameLayout>

fragment3

package com.example.ex0430;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class Fragment3 extends Fragment {
    EditText edtUrl;
    Button btnSave;

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

        View view = inflater.inflate(R.layout.fragment_3, container, false);
        edtUrl = view.findViewById(R.id.edtUrl);
        btnSave = view.findViewById(R.id.btnSave);

        //SharedPreferences
        // : 앱의 데이터를 저장하기 위한 객체
        // : 간단한 데이터를 key, Value형태로 저장 -> 안드로이드 내부에 XML파일로 저장
        // Context.MODE_PRIVATE
        // : 외부 앱에서 접근이 불가하게 만드는 설정 값
        SharedPreferences spf = getActivity().
                getSharedPreferences("mySPF", Context.MODE_PRIVATE);

        //editor 실행시키는?
        SharedPreferences.Editor editor = spf.edit();

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //사용자가 URL값을 입력하면 저장
                String url = edtUrl.getText().toString();

                //URL값을 mySPF.xml 파일에 url값을 저장
                editor.putString("url",url);
                editor.commit();
                //getActivity() -> MainActivity
                Toast.makeText(getActivity(),"새로운 주소가 설정",Toast.LENGTH_SHORT).show();
            }
        });

        return view;
    }
}

fragment3.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".Fragment3">

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="340dp"
        android:text="@string/btnSave"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/edtUrl"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="@+id/edtUrl" />

    <EditText
        android:id="@+id/edtUrl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/edtUrl_hint"
        android:inputType="textPersonName"
        android:textAlignment="center"
        app:layout_constraintBottom_toTopOf="@+id/btnSave"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.888" />
</androidx.constraintlayout.widget.ConstraintLayout>
profile
초보 코딩

0개의 댓글