'2017/03/17'에 해당되는 글 2건

728x90

본 내용은 강의 수강 내용과 인터넷 검색해서 보강한 자료를 기록해둔다.

AsyncTask 는 Thread 보다 자주 사용하며, MySQL(PHP) 서버와의 통신에서도 사용한다.

import 추가는 Alt + Enter 를 누르라고 팝업 알림창이 나온다. 그러면 눌러주면 된다.

Android Studio 는 오프라인 강의를 들었는데, 단축키 기능이 너무 편리하다.

XML 코드 작성시에도 기본적인 것부터 작성할 수 있게 하고 명령어를 일부 넣어주면 자동으로 팝업되면서 자동완성 기능을 편하게 완성시킨다.


package com.tistory.link2me.app10;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button btn_alert;
    Button btn_custom;
    Button btn_progress;
    TextView txt;
    ProgressDialog progressDialog;

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

        btn_alert = (Button) findViewById(R.id.btn01);
        btn_custom = (Button) findViewById(R.id.btn02);
        btn_progress = (Button) findViewById(R.id.btn03);
        txt = (TextView) findViewById(R.id.tv01);

        btn_alert.setOnClickListener(listener);
        btn_custom.setOnClickListener(listener);
        btn_progress.setOnClickListener(listener);
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.btn01:
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("2017 프로야구 우승후보")
                            .setMessage("두산 베어스")
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(getBaseContext(), "OK", Toast.LENGTH_LONG).show();
                                    txt.setText("두산 베어즈");
                                }
                            })
                            .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(getBaseContext(), "NO", Toast.LENGTH_LONG).show();
                                    txt.setText("LG 트윈스");
                                }
                            })
                            .show();
                    break;

                case R.id.btn02:
                    LinearLayout linearLayout = (LinearLayout) View.inflate(MainActivity.this, R.layout.custom, null);
                    final EditText editText = (EditText) linearLayout.findViewById(R.id.et01);

                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("2017 프로야구 우승 후보")
                            .setView(linearLayout)
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(getBaseContext(), "OK", Toast.LENGTH_LONG).show();
                                    String winner = editText.getText().toString();
                                    txt.setText(winner);
                                }
                            })
                            .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(MainActivity.this, "CANCEL", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .show();
                    break;

                case R.id.btn03:
                    DownloadTask task = new DownloadTask(MainActivity.this);
                    task.execute(100);
                    break;
            }
        }
    };

    private class DownloadTask extends AsyncTask<Integer, String, Integer> {

        ProgressDialog progressDialog;
        private Context mContext;

        public DownloadTask(Context context){
            mContext =context;
        }

        @Override
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setIcon(android.R.drawable.ic_dialog_info);
            progressDialog.setTitle("Download");
            progressDialog.setMessage("다운로드 중...");
            progressDialog.show(); // show dialog

            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(Integer... params) {
            //doInBackground 함수는 excute() 실행시  실행됨
            final int taskCnt = params[0]; // 최대 몇인지 설정하는 변수
            publishProgress("max", Integer.toString(taskCnt));
            try {
                for (int i = 0; i < taskCnt; i++) {
                    publishProgress("progress", Integer.toString(i), "번호 " + Integer.toString(i) + "번 수행중");
                    Thread.sleep(100);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return taskCnt; // onPostExecute()함수의 인수가 됨
        }

        @Override
        protected void onProgressUpdate(String... progress) {
            //onProgressUpdate() 함수는 publishProgress() 함수로 넘겨준 데이터들을 받아옴
            if (progress[0].equals("progress")) {
                progressDialog.setProgress(Integer.parseInt(progress[1]));
                progressDialog.setMessage(progress[2]);
            }
            else if (progress[0].equals("max")) {
                progressDialog.setMax(Integer.parseInt(progress[1]));
            }
        }

        @Override
        protected void onPostExecute(Integer result) {
            //onPostExecute() 함수는 doInBackground() 함수가 종료되면 실행됨
            progressDialog.dismiss();
            super.onPostExecute(result);
        }
    }
}


첨부한 파일은 Android Studio 에서 프로젝트 생성하고 첨부한 파일을 참조해서 작성하면 도움이 된다.

app_main.zip



블로그 이미지

Link2Me

,
728x90

Android Studio 에서 xml 파일을 추가하는 방법

오랫만에 접속하면 이런 방법마저 잊어버리게 되더라. 그래서 적어둔다.




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

<ImageButton
android:id="@+id/ib01"
android:src="@android:drawable/sym_def_app_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<EditText
android:id="@+id/et01"
android:hint="예상 우승 후보팀을 입력하세요"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

이 XML 파일을 View 객체로 만들기 위해서는 LayoutInflator를 이용해야 한다.

안드로이드에서 inflate 를 사용하면 xml 에 씌여져 있는 view 의 정의를 실제 view 객체로 만드는 역할을 한다.

자바 프로그램 코드상에서는 레이아웃 인플레이터에 직접 접근하지 못하고

getLayoutInflater() 메소드를 이용하거나, getSystemService(String) 메소드를 호출해 반환값으로 LayoutInflater 객체를 받아야 한다.

사용자의 화면에 보여지는 것들은 Activity 위에 있는 View다.


Layout Inflater
- 레이아웃 인플레이터는 레이아웃 xml 파일에 상응하는 뷰 객체를 반환받는 데 사용한다
- 자바 프로그램 코드상에서는 레이아웃 인플레이터에 직접 접근하지 못하고 getLayoutInflater() 메소드를 이용하거나
getSystemService(String) 메소드를 호출해 반환값으로 LayoutInflater 객체를 받아야 한다.
- 보통 자바 코드에서 View, ViewGroup 을 사용하거나, Adapter의 getview() 또는 Dialog, Popup 구현시
배경화면이 될 Layout을 만들어 놓고 View의 형태로 반환 받아 Acitivity에서 실행 하게 된다.


inflate(int resource, ViewGroup root, boolean attachToRoot)
- 레이아웃 XML파일을 View객체로 만들기 위해서는 LayoutInflater내의 inflater 메서드를 사용
- resource: view를 만들고 싶은 레이아웃 파일의 id (
inflate할 대상의 xml 리소스)

ex) R.layout.custom

- 두 번째 인수는 생성된 뷰의 루트로 사용할 뷰 객체. 리소스 내에 루트가 따로 있다면 null.


inflate 를 사용하기 위해서는 우선 inflater 를 얻어와야 한다.
LayoutInflater inflater = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE );
LinearLayout linearLayout = (LinearLayout) inflater.inflate( R.layout.custom, null);
setContentView( linearLayout ); // 가져온 View 를 화면에 그린다.


/* We get the inflator in the constructor */
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

--> getSystemService(Context.LAYOUT_INFLATER_SERVICE) = LayoutInflater 객체를 반환받는다.


// 인플레이트를 얻어오는 다른 방법
LinearLayout linearLayout = (LinearLayout) View.inflate(MainActivity.this, R.layout.custom, null);
// Inflate된 View에서 Child인 EditText를 얻어 오기
EditText editText = (EditText) linearLayout.findViewById(R.id.et01);




블로그 이미지

Link2Me

,