본문 바로가기

Development/Android Studio

(Android Studio) Chapter3. ListView, Navigation Menu, Shared Preferences, Web View

1. ListView

    - 리스트형식의 레이아웃으로 데이터를 나열하여 보여줌

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >


    </ListView>


</LinearLayout>

    - .java

package com.example.listexample01;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView list;


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

        list = (ListView) findViewById(R.id.list);

        List<String> data = new ArrayList<>();  // 제네릭, collections framework

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);
        // 어뎁터를 인스턴스화해서 기본 제공되는 레이아웃을 가져옴
        list.setAdapter(adapter);
        data.add("Loquens");            // 데이터 추가
        data.add("Rudens");
        data.add("Sapiens");
        adapter.notifyDataSetChanged(); // 데이터 저장 완로 선언
    }
}

 

2. Navigation Menu

  1) 기본 기능 구성

  - 네비게이션 관련 메소드(java)

    onCreate : 앱의 시작지점을 구성

    FloatingActionButton fab : 창띄우기 기능, 스낵바(Toast 보다 더 세련된 나중에 나온 기능) 메세지 포함

    onBackPressed : 백버튼 눌렀을 때 액션 지정

    onClick : 클릭 시 실행 될 액션들 설정

    onCreateActionMenu

    onNavigationItemSelected(MenuItem item) : 네비게이션 메뉴 포함(기능의 핵심들)

  - 네비게이션 관련 ActivityMain.xml

    <include /> 안에 다음의 내용 포함

    기본 시작 화면 구성 + NavigationView의 레이아웃 구성

  - activity_main_drawer.xml

    action_main.xml의 내부 디자인(아이콘, 텍스트 등) 변경

  - app_bar_main

    앱바 지정

 

※ MainActivity.java 는 xml 파일에서 구성된 버튼, 앱바 등의 아이콘에 액션을 지정, id 지정을 통해 불러와서 기능 선언

※ activity_main.xml 파일은 전체 레이아웃을 포함, 네비게이션도 여기에서 선언

※ app_bar_main.xml 은 전체 레이아웃 이외의 플로팅 버튼 레이아웃 저장

※ activity_main_drawer.xmld은 레이아웃에 사용될 그림들을 저장

 

  2) 커스텀

기본 제공 템플릿 사용 이외에 메뉴를 커스텀하여 직접 구성하는 방법

  - java(기본 제공 기능 import 후 해당 기능에 override하면서 main과 drawer의 id를 불러와 기능을 추가해줌)

package com.example.customnaviexample;

import android.support.annotation.NonNull;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout drawerLayout;
    private View drawerView;

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

        drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        drawerView = (View)findViewById(R.id.drawer);

        Button btn_open = (Button) findViewById(R.id.btn_open);
        btn_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(drawerView);
            }
        });

        Button btn_close = (Button)findViewById(R.id.btn_close);
        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.closeDrawers();
            }
        });

        drawerLayout.setDrawerListener(listener);
        drawerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });


    }

    DrawerLayout.DrawerListener listener = new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(@NonNull View view, float v) {

        }

        @Override
        public void onDrawerOpened(@NonNull View view) {

        }

        @Override
        public void onDrawerClosed(@NonNull View view) {

        }

        @Override
        public void onDrawerStateChanged(int i) {

        }
    };
}

  - activity_main.xml (메인페이지의 기능을 작성 + 네비게이션 open기능을 추가)

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

        <Button
            android:id="@+id/btn_open"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="열려라 참깨" />

    </LinearLayout>
    <include layout="@layout/activity_drawer" />

</android.support.v4.widget.DrawerLayout>

  - activity_drawer.xml (네비게이션이 열렸을 때 보이는 버튼 선언 + 닫힘버튼 추가, 버튼 없이 네비게이션외부 영역 터치되면 닫히는 기능으로 실현하는 것으로 확장해 볼 것)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:id="@+id/drawer"
    android:background="#2BA8B8"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_close"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="메뉴닫기"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Loquens 메뉴" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="#F6EFEF"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="테스트 메뉴" />
    </LinearLayout>

</LinearLayout>

 

 

 

3. Shared Preferences

  1) Java

package com.example.sharedexample;

import static android.os.Build.VERSION_CODES.O;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    EditText et_save;
    String shared = "file";

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

        et_save = (EditText) findViewById(R.id.et_save);

        SharedPreferences sharedPreferences = getSharedPreferences(shared, 0);
        String value = sharedPreferences.getString("Loquens", "");
        et_save.setText(value);  // 시작 값에서 저장된 위 행의 스트링 값을 셋팅을 하겠다.

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        SharedPreferences sharedPreferences = getSharedPreferences(shared, 0);
        SharedPreferences.Editor editor = sharedPreferences.edit(); // 저장할 때는 editor를 불러와야함
        String value = et_save.getText().toString();  // 안드로이드 환경에서 텍스트가 입력된 것을 스트링으로 받아오겠다.
        editor.putString("Loquens", value);  // 받아온 스트링을 스트링 형태로 저장하겠다.
        editor.commit();  // save를 완료해라.
    }
}

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


    <EditText
        android:id="@+id/et_save"
        android:layout_width="100dp"
        android:layout_height="wrap_content" />




</LinearLayout>

 

4. WebView

  - 홈페이지 불러오기

  - 뒤로가기 눌렀을 때 안드로이드 상 뒷페이지로 가기 기능 추가 예시

  1) java

package com.example.webviewexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity<webView> extends AppCompatActivity {

    private WebView webView;
    private String url = "https://www.naver.com";

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

        webView = (WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);
        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClientClass());

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private class WebViewClientClass extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
}

 

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

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

  3) AndroidMenifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.webvidewexample">

    <uses-permission android:name="android.permission.INTERNET" />