안드로이드 스튜디오 Fragment, AlertDialog, Snackbar 사용하기



Fragment란?

아래 사이트에 잘 나와있습니다.

- https://developer.android.com/guide/components/fragments.html?hl=ko#Design



public class Fragment1 extends Fragment {

@Nullable

@Override


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

this.inflater = inflater;

v = inflater.inflate(R.layout.fragment1, container, false );

return v;

}


Fragment를 extends 하고 Fragment에 붙일 layout을 작성하고 inflate를 해줍니다.


그리고 Fragment를 붙이고 싶은 Activity의 layout에 아래 코드를 추가합니다.


<fragment

    android:id="@+id/fragment"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:name="com.examples.androidpractice4_1.Fragment1"

/>


 name에는 들어가는 Activity에 들어가는 Fragment의 위치를 작성해줍니다.




AlertDialog는 안드로이드의 대화상자를 말합니다.


기본적인 형태의 AlertDialog는 Activity 코드 작성만을 통해 사용할 수 있습니다.

AlertDialog.Builder dialog = new AlertDialog.Builder(this);

dialog.setTitle("제목")
.setMessage("내용")
.setNegativeButton("닫기", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

}
})
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

}
})
.show();

setTitle은 제목 설정, setMessage는 내용설정 

setNegativeButton은 왼쪽에 있는 버튼

setPositiveButton은 오른쪽에 있는 버튼을 나타냅니다.

그리고 new OnClickListener 설정을 통해서 버튼 클릭 이벤트를 설정해 줄 수 있습니다.


AlertDialog의 모양을 원하는대로 바꾸고 싶다면 새로운 xml 파일을 만들고 .setView(int layoutResId)를 통해 붙여주면 됩니다.




Snackbar를 사용하기 위해서는 dependecy를 추가해야합니다.

File에서 ProjectStructure를 클릭해서 들어갑니다.


그리고 Dependencies를 클릭하고 + 버튼을 클릭합니다.


그리고 design을 입력하고 나오는 칸을 클릭하고 Ok를 누르면 Snackbar를 사용할 수 있습니다.


아래 앱은 Fragment, AlertDialog, Snackbar 사용해서 만든 앱입니다.


 

-

 

-

 


-


깃 허브 주소입니다.


https://github.com/Ywook/Android.practice4_1











안드로이드 TabHost 사용해서 앱 만들기 


TabHost를 사용하고자 하는 layout 파일에 tabHost를 추가해줍니다.


TabHost의 layout을 작성한 후에 자바 파일에서 TabHost를 추가해줍니다.


mTabHost = (TabHost)findViewById(R.id.tabhost);
mTabHost
.setup();


코드를 실행해보면 아직 Tab이 추가가 안된 화면을 볼 수 있는데 이유는 addTab을 하지 않았기 때문입니다


TabSpec를 만들고 addTab을 해주면 화면에 Tab이 추가된 것을 볼 수 있습니다.


여기서 newTabSpec에 들어가는 String은 Tab에 대한 specification을 추가하는 것이고 반드시 null이 아니여야 합니다.


setContent를 통해 추가하길 원하는 tab의 아이디를 넣고 setIndicator에서 Tab에 나타나는 글자를 설정해줄 수 있습니다.


TabHost.TabSpec tab1 = tabHost.newTabSpec("1").setContent(R.id.tab1).setIndicator("Tab1 이름");

TabHost.TabSpec tab2 = tabHost.newTabSpec("2").setContent(R.id.tab2).setIndicator("Tab2 이름");


mTabHost.addTab(tab1);

mTabHost.addTab(tab2);




 



 





위 앱은 TabHost를 사용해서 만들었습니다.


앱의 전체 코드는 GitHub에서 볼 수 있습니다.


https://github.com/Ywook/Ss3-2





안드로이드 옵션 메뉴(OptionMenu) 사용해서 앱 만들기



안드로이드에서 옵션 메뉴를 사용하기 위해서는 세 단계를 걸쳐야합니다.


메뉴 xml파일 생성 -> 자바파일 작성을 통해 액티비티에 메뉴 붙이기 -> 메뉴 별로 기능 구현하기


res폴더 안에 menu폴더가 있으면 menu.xml을 생성하고 menu폴더가 없으면 menu폴더를 만든후 menu.xml파일을 생성합니다.






menu.xml 파일에 넣고 싶은 item들을 넣은 후에 옵션 메뉴를 사용하고자 하는 Activity의 자바 파일에서


onCreateOptionMenu() 메소드를 Override 한 후 MenuInflater를 통해 옵션 메뉴를 객체화 시켜줍니다.

@Override

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.menu, menu);

return super.onCreateOptionsMenu(menu);

}


그리고 onOptionItemSelected(MenuItem item) 메소드를 Override 하고 메뉴의 기능을 구현해줍니다.

@Override

public boolean onOptionItemSelected(MenuItem item) {

switch (item.getItemId()){

case R.id.mnu:

layout.setBackgroundColor(Color.RED);

break;

return super.onOptionItemSelected(item);

}




 


 


 




위의 앱은 옵션 메뉴(OptionMenu)를 사용해서 만들었습니다.


여태까지 만들었던 앱에는 없었던 그림 회전하기와 그림 2배 확대하기를 추가했습니다.


그림을 회전하기 위해서는 setRotation(float rotation) 메소드를 호출하면 되는데 이 메소드는 처음 각도를 기준으로 들어오는 수 만큼


각도를 바꾸는 메소드입니다.


그림을 2배 확대하기 위한 메소드는 setScaleX(float scale), setScaleY(float scale) 메소드를 사용했습니다.


처음 비율을 기준으로 들어오는 scale만큼 x, y의 넓이를 확대시켜주는 메소드입니다.


확대를 적용하고 싶지 않다면 scale값을 1을 넣어주면 처음처럼 돌아갑니다.



위 앱의 모든 코드는 GitHub에서 볼 수 있습니다.


https://github.com/Ywook/Ss3-1


 






안드로이드 RelativeLayout 사용하기



RelativeLayout은 상대적 위치에 기반하여 뷰들을 배치하는 layout입니다.


이 layout을 사용할 경우에는 기준이 되는 어떤 뷰의 왼쪽, 오른쪽, 위, 아래에 배치하는 방식으로 뷰를 배치해야 합니다.


android:layout_alignTop="@id/tag" tag라는 이름을 가진 뷰의 상단 가장자리에 배치


android:layout_alignBaseline="@id/tag" tag라는 이름을 가진 뷰의 중간자리에 배치


android:layout_alignBottom="@id/tag" tag라는 이름을 가진 뷰의 하단 가장자리에 배치


android:layout_above="@id/tag" tag라는 이름을 가진 뷰 위에 배치


android:layout_below="@id/tag" tag라는 이름을 가진 뷰 아래에 배치


android:layout_toRightOf="@id/tagtag라는 이름을 가진 뷰 오른쪽에 배치


android:layout_toLeftOf="@id/tag" tag라는 이름을 가진 뷰 왼쪽에 배치


android:layout_alignLeft="@id/tagtag라는 이름을 가진 뷰의 왼쪽 가장자리에 배치


android:layout_alignRight="@id/tagtag라는 이름을 가진 뷰의 오른쪽 가장자리에 배치




위의 속성들을 적용해서 만든 화면입니다.


android:layout_alignTop="@id/기준위젯"

android:layout_toLeftOf="@id/기준위젯


두 개의 속성을 동시에 사용하면  1번 자리에 배치됩니다.


android:layout_alignBaseline="@id/기준위젯"

android:layout_toLeftOf="@id/기준위젯"


2번자리에 배치됩니다.



위의 코드는 GitHub에서 볼 수 있습니다.

https://github.com/Ywook/layout/blob/master/app/src/main/res/layout/relativelayout.xml


안드로이드 스튜디오 FrameLayout, GridLayout, LinearLayout 사용해서 앱 만들기



GridLayout은 TableLayout과 비슷하게 위젯을 표 형식으로 배치할 때 사용하는 Layout인데  


TableLayout은 할 수 없는 행 병합을 할 수 있어서 더 다양하게 만들 수 있습니다.


GridLayoutandroid:rowCount="", android:columnCount="" 속성을 사용해서 row와 column을 미리 지정할 수 있습니다.


GridLayout에 포함되어 있는 위젯에 android:layout_row="android:layout_column="속성을 지정해줘서 해당 위젯)가


몇 번째 행, 몇 번째 column에 위치할 지 지정해 줄 수 있습니다.


android:layout_rowSpan="" , android:layout_columnSpan="" 을 사용해서 몇 개의 행, 열을 합쳐서 사용할지 지정하고


android:layout_columnWeight="", android:layout_rowWeight="" 를 통해 행과 열의 비율을 지정해서 사용할 수 있습니다.




FrameLayout은 위젯을 겹처서 사용하고 싶을때 사용하는 layout입니다.


버튼이 클릭될때 화면이 전환되는 것처럼 보여주기 위해  FrameLayout안에 DatePickerTimePickerLinearLayoutGridLayout을 넣고


위젯의 visibility가 상황에 따라 변하게 설정해 주었습니다.


LinearLayout은 위젯을 수직 혹은 수평으로 배치할 수 있는 layout입니다.


수직으로 배치하고 싶으면 android:orientation="vertical" ,


수평으로 배치하고 싶으면 android:orientation="horizontal" 을 사용하면 됩니다. 







위의 앱은 GridLayout, FrameLayout, LinearLayout을 사용했습니다.


TextView, EditText, Button 외에도 SwitchChronometer, DatePicker, TimePicker를 사용했습니다.


Switch는 두 개의 상태를 표시하는 버튼입니다.


자바 파일에서 .setOnCheckedChangeListener() 이벤트 설정을 통해 상태에 따른 효과를 다르게 줄 수 있습니다.


Chronometer는 시간을 측정하는 위젯입니다.


자바 파일에서 .start()를 통해 Count를 시작 할 수 있고 .stop()을 통해 정지 시킬 수 있습니다.


만약 다시 00:00으로 reset하고 싶으면 .setBase(SystemClock.elapsedRealtime()) 를 사용합니다.


DatePicker는 날짜를 표시하는 위젯입니다.


선택된 정보를 가져오기 위해서는 getYear(), getMonth(), getDayOfMonth()를 사용하는데


DatePicker에서 선택된 정보는 int로 반환되기 때문에 String으로 사용하고 싶다면 형 변환을 해야합니다.

String year = Integer.toString(datePicker.getYear());

String month = Integer.toString(datePicker.getMonth() + 1);

String day = Integer.toString(datePicker.getDayOfMonth());


TimePicker는 시간을 표시하는 위젯입니다.


TimePicker에서 선택된 정보도 int로 반환되기 때문에 String으로 사용하고 싶다면 형 변환을 해야합니다.

String hour = Integer.toString(timePicker.getCurrentHour()) ;

String minute = Integer.toString(timePicker.getCurrentMinute());


아마 TimePicker의 getCurrentHour()와 getCurrentMinute()의 중앙에 밑줄이 그어져 있을텐데


이유는 API 23이후에는 getCurrentHour(), getCurrentMinute()가 사라지고 getHour()와 getMinute()으로 대체되기 때문입니다


저는 API 16을 기준으로 앱을 만들었기 때문에 그냥 getCurrentHour(), getCurrentMinute() 를 사용했습니다.


Button이 실행 중 작동하지 않게 하게 하려면 .setEnabled(false) 다시 작동하게 하려면 Button에 .setEnabled(true)을  사용합니다.


그리고 .setEnabled(false)로 설정된 버튼이 다시 작동하게 하기 위해서는 .setEnabled(true) 값을 설정해 주면 됩니다.



위 앱의 모든 코드는 GitHub에서 볼 수 있습니다!


https://github.com/Ywook/Android.Practice2_2






안드로이드 스튜디오 TableLayout 사용해서 학점 계산 앱 만들기



TableLayout은 위젯을 표 형식으로 배치할 때 사용하는 layout입니다.


TableRow로 테이블에 행을 하나씩 추가하고, 추가한 행에 위젯들을 배치합니다.


TableLayout은 행 병합은 할 수 없만 속성을 이용해서 열 병합을 할 수 있습니다.


android:layout_span="n" 은 n개의 column을 병합해서 한 개의 column으로 표시하라는 뜻입니다. 


android:stretchColumns="" 은 column을 지정해서 해당 column이 row를 가득 채우도록 하는 속성입니다.


"" 안에 0, 1, 2 이런 식으로 다수의 column을 지정해 줄 수도 있고 모든 Column에게 적용하고 싶으면 *를 넣어주면 됩니다.


android:visibility="visible" 은 화면에 표시하라는 속성

android:visibility="invisible" 은 화면에서 보이지 않게 하라는 속성

android:visibility="gone" 은 화면에서 보이지도 않고 공간도 차지하지 않게하는 속성입니다.


즉, invisibler과 gone은 둘 다 화면에서 보이지 않지만 invisible은 공간은 차지하고 있고 gone 공간도 차지하지 않게 한다는 뜻입니다.


visiblity 속성을 지정해주지 않았다면 기본으로 VISIBLE이 적용되어 화면에 표시됩니다.


xml 파일이 아닌 자바파일에서 적용을 하고 싶다면 적용하고 싶은 뷰(View)에 


.setVisibility(View.VISIBLE);

.setVisibility(View.INVISIBLE);

.setVisibility(View.GONE);


중 원하는 속성을 적용 시키면 됩니다.


ImageView는 이미지를 표시할 수 있는 위젯입니다. 


이미지를 설정해주기 위해서 xml 파일에서 android:src=""을 사용하거나 자바 파일에서 .setImageResource()를 사용해주면 됩니다.


text의 Color를 바꾸고 싶다면 android:textColor="#FFFFFF를 이용해서 색을 변경할 수 있습니다.(#FFFFFF은 흰색입니다.)


배경색을 바꾸고 싶다면 android:background=""를 이용하면 됩니다!


밑에 앱은 TextView의 textColor와 TableLayout의 background의 색을 설정하고


ImageView, EditText, Button, TextView를 사용하여 만들었습니다.


  




위 앱의 전체 코드는 gitHub에서 볼 수 있습니다.


https://github.com/Ywook/Android.Practice2_1

안드로이드 스튜디오 기본 위젯(Widget)을 사용한 앱 만들기 (2)


안드로이드 스튜디오 기본 위젯(Widget)을 사용한 앱 만들기 (1)



이전글에서 추가한 Actvity를 차례대로 완성해보겠습니다.


아래 코드는 사과가격 계산의 xml입니다.

여기서 EditText의  android:hint="는 글자를 입력하지 않을때 " "안의 글자가 흐릿하게 보이게하는 속성입니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_margin="20dp"
android:layout_height="match_parent"
tools:context="examples.com.myapplication2.Main2Activity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="사과의 가격은?"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="숫자로 입력"
android:id="@+id/editText"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="사과의 개수는?"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="숫자로 입력"
android:id="@+id/editText2"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="총 금액 계산하기"/>
</LinearLayout>



사과가격 계산의 자바 소스입니다.

여기서 setTitle("")은 액션바에 나타나는 글자를 설정할 수 있는 메소드입니다.


EditText에 작성되어 있는 text는 getText()로 얻을 수 있는데 반환 형식이 Text이므로 String으로 받기 위해

.toString()을 통해 형변환을 시켜줍니다.


Toast.makeText().show(); 통해 화면 하단에 메세지를 띄울 수 있습니다.

첫번째 인자로 현재 Activity가 들어가고 

두번째 인자로 출력하고 싶은 내용

세번째 인자로 Toast.LENGTH_SHORT, Toast.LENGTH_LONG을 선택해서 보여주는 시간을 설정할 수 있습니다. 


package examples.com.myapplication2;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main2Activity extends AppCompatActivity {
EditText e1, e2;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setTitle("사과가격 계산기");
init();
}

void init(){
e1 = (EditText)findViewById(R.id.editText);
e2 = (EditText)findViewById(R.id.editText2);
b1 = (Button)findViewById(R.id.btn);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String price = e1.getText().toString();
String count = e2.getText().toString();
int result = Integer.parseInt(price)*Integer.parseInt(count);

Toast.makeText(getApplicationContext(),"사과의 가격은 " + result, Toast.LENGTH_SHORT).show();
}
});
}

} 



실행화면입니다.





사과가격 계산하기와 같은 방법으로 만든 나이계산기의 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:orientation="vertical"
android:layout_margin="20dp"
android:layout_height="match_parent"
tools:context="examples.com.myapplication2.Main3Activity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="태어난 년도를 입력하세요."/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="숫자를 입력하세요."
android:id="@+id/age_edit"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="나이계산"
android:id="@+id/age_btn"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="나이를 입력하세요."/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="숫자를 입력하세요."
android:id="@+id/age_edit2"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/age_btn2"
android:text="태어난 해 계산"/>

</LinearLayout> 



나이계산기의 자바 소스입니다.
package examples.com.myapplication2;

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.Toast;

public class Main3Activity extends AppCompatActivity {
int YEAR = 2017;
EditText e1, e2;
Button btn1, btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
setTitle("나이계산기");
init();
}

public void init(){
btn1 = (Button) findViewById(R.id.age_btn);
btn2 = (Button) findViewById(R.id.age_btn2);
e1 = (EditText)findViewById(R.id.age_edit);
e2 = (EditText)findViewById(R.id.age_edit2);

btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String temp = e1.getText().toString();
int age = YEAR - Integer.parseInt(temp) + 1;
Toast.makeText(getApplicationContext(),"당신의 나이는 " + age + "세 입니다.",Toast.LENGTH_SHORT).show();
}
});

btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String temp = e2.getText().toString();
int result = YEAR - Integer.parseInt(temp) +1;
Toast.makeText(getApplicationContext(),"당신의 태어난 해는 "+result+"년 입니다.",Toast.LENGTH_SHORT).show();
}
});
}

} 



실행화면입니다.




나이계산기와 동일한 방법으로 만든 온도변환기 xml 코드 입니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_margin="20dp"
android:layout_height="match_parent"
tools:context="examples.com.myapplication2.Main3Activity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="섭씨 온도를 입력하세요."/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="온도를 입력하세요."
android:id="@+id/h2_edit"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="화씨계산"
android:id="@+id/h2_btn"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="화씨 온도를 입력하세요."/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="온도를 입력하세요."
android:id="@+id/h2_edit2"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/h2_btn2"
android:text="섭씨계산"/>

</LinearLayout> 


온도변환기의 자바 소스입니다.

 package examples.com.myapplication2;


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main4Activity extends AppCompatActivity {
EditText e1, e2;
Button btn1, btn2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
setTitle("온도변환기");
init();
}
public void init(){
btn1 = (Button) findViewById(R.id.h2_btn);
btn2 = (Button) findViewById(R.id.h2_btn2);
e1 = (EditText)findViewById(R.id.h2_edit);
e2 = (EditText)findViewById(R.id.h2_edit2);

btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String temp = e1.getText().toString();
double result = Integer.parseInt(temp)*1.8 + 32;
Toast.makeText(getApplicationContext(),"화씨 온도는 " + result + "도 입니다.",Toast.LENGTH_SHORT).show();
}
});

btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String temp = e2.getText().toString();
double result = (Integer.parseInt(temp)-32)/(1.8);
Toast.makeText(getApplicationContext(),"섭씨 온도는 "+result+"도 입니다.",Toast.LENGTH_SHORT).show();
}
});
}
}



실행화면입니다.




레스토랑 주문의 xml 코드 입니다.

위의 코드에서 android:weightSum과 android:layout_weight 라는 새로운 속성이 추가되었습니다.

weightSum을 통해 비율의 합을 정해주고 layout_weight를 통해 비율을 나눠 줄 수 있습니다.

예를 들어 layout안의 두 개의 뷰(View)를 4:3으로 나눠서 사용하고 싶다면 layout에 weightSum을 7을 주고 

두개의 뷰(View)의 layout_weight를  각각 4, 3을 주고 

가로로 비율을 주고 싶으면 width에 0dp, 세로로 비율을 주고 싶으면 height에 0dp를 줘서 사용할 수 있습니다.


그리고 android:textStyle="" 를 통해 뷰(View) 에 들어있는 텍스트의 스타일을 변경해 줄 수 있습니다. 

안드로이드 스튜디오는는 bold, italic, normal을 기본으로 지원하는데 CheckBox와 Button의 텍스트를 진하게

보여주기 위해서 bold 속성을 추가했습니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:layout_margin="20dp"
tools:context="examples.com.myapplication2.Main5Activity">


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


<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="피자(15000원)" />

<EditText
android:id="@+id/h3_edit"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="개수 입력"/>

</LinearLayout>

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


<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="스파게티(13000원)" />

<EditText
android:id="@+id/h3_edit2"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="개수 입력"/>

</LinearLayout>

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


<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="샐러드(9000원)" />

<EditText
android:id="@+id/h3_edit3"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="개수 입력"/>

</LinearLayout>

<CheckBox
android:id="@+id/checkBox"
android:layout_width="match_parent"
android:textStyle="bold"
android:layout_height="wrap_content"
android:text="멤버쉽 카드 있음(10%할인)" />

<Button
android:id="@+id/h3_btn"
android:layout_width="match_parent"
android:textStyle="bold"
android:layout_height="wrap_content"
android:text="금액 계산하기" />

<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:weightSum="7"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="주문개수"/>

<TextView
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:id="@+id/h3_text"
android:text="0개" />
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:weightSum="7"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="주문개수"/>

<TextView
android:layout_width="0dp"
android:id="@+id/h3_text2"
android:layout_weight="2"
android:layout_height="wrap_content"
android:text="0개" />
</LinearLayout>


</LinearLayout> 



레스토랑 주문의 자바 소스입니다.

CheckBox의 isChecked()는 CheckBox가 Check되어 있으면 true 아닐경우 false를 반환하는 메소드입니다.

true일 경우 10퍼센트 할인된 가격을 출력합니다.

package examples.com.myapplication2;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;


public class Main5Activity extends AppCompatActivity {
EditText e1, e2, e3;
Button btn;
CheckBox checkBox;
TextView text1,text2;
int PIZZA = 15000, SPAGHETTI = 13000, SALAD = 9000;
double DISCOUNT = 0.9;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
setTitle("레스토랑 주문");

init();

}



void init() {
e1 = (EditText) findViewById(R.id.h3_edit);
e2 = (EditText) findViewById(R.id.h3_edit2);
e3 = (EditText) findViewById(R.id.h3_edit3);

btn = (Button) findViewById(R.id.h3_btn);

checkBox = (CheckBox) findViewById(R.id.checkBox);

text1 = (TextView) findViewById(R.id.h3_text);
text2 = (TextView) findViewById(R.id.h3_text2);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int t1 = Integer.parseInt(e1.getText().toString());
int t2 = Integer.parseInt(e2.getText().toString());
int t3 = Integer.parseInt(e3.getText().toString());

int result1 = t1 + t2 + t3;
int result2 = t1 * PIZZA + t2 * SPAGHETTI + t3 * SALAD;


if (checkBox.isChecked()) {
result2 = (int) (result2 * DISCOUNT);
}

text1.setText(result1+"개");
text2.setText(result2+"원");
}
});
}
}

실행화면입니다.




계산기의 xml 소스 입니다.

레스토랑 주문하기와 비슷하게 layout_weight를 사용하여 만들었습니다.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_margin="20dp"
android:layout_height="match_parent"
tools:context="examples.com.myapplication2.Main6Activity">

<LinearLayout
android:orientation="horizontal"
android:weightSum="10"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_weight="1.35"
android:layout_height="wrap_content"
android:text="숫자 1 "/>
<EditText
android:layout_width="0dp"
android:layout_weight="8.65"
android:layout_height="wrap_content"
android:hint="정수 입력"
android:id="@+id/h4_edit"/>
</LinearLayout>

<LinearLayout
android:orientation="horizontal"
android:weightSum="10"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_weight="1.35"
android:layout_height="wrap_content"
android:text="숫자 2 "/>
<EditText
android:layout_width="0dp"
android:layout_weight="8.65"
android:layout_height="wrap_content"
android:hint="정수 입력"
android:id="@+id/h4_edit2"/>
</LinearLayout>

<Button
android:id="@+id/h4_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="더하기" />

<Button
android:id="@+id/h4_btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="빼기" />

<Button
android:id="@+id/h4_btn3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="곱하기" />

<Button
android:id="@+id/h4_btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="나누기" />

</LinearLayout> 



계산기의 자바 소스입니다.

EditText에 글을 적지 않았을 때는 null이 반환되고 글을 적었다 지웠을때는 빈 String인 ""이 반환됩니다.

따라서 EditText가 비었는지 체크하는 isEmpty() 메소드를 하나 만들고

EditText가 비었을 경우 Toast 메세지를 출력하고 입력이 되지 않은 곳에 .requsetFocus()를 사용하여 포커스를 줍니다.


package examples.com.myapplication2;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main6Activity extends AppCompatActivity {
EditText e1, e2;
Button btn1, btn2, btn3, btn4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main6);
setTitle("계산기");

init();
}

void init(){
e1 = (EditText)findViewById(R.id.h4_edit);
e2 = (EditText)findViewById(R.id.h4_edit2);

btn1 = (Button)findViewById(R.id.h4_btn);
btn2 = (Button)findViewById(R.id.h4_btn2);
btn3 = (Button)findViewById(R.id.h4_btn3);
btn4 = (Button)findViewById(R.id.h4_btn4);

btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String s1 = e1.getText().toString();
String s2 = e2.getText().toString();

if(emptyCheck(s1, s2));
else{
int result = Integer.parseInt(s1)+Integer.parseInt(s2);
Toast.makeText(getApplicationContext(), "더하기 계산 결과는 "+result+"입니다",Toast.LENGTH_SHORT).show();
}
}
});

btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String s1 = e1.getText().toString();
String s2 = e2.getText().toString();

if(emptyCheck(s1, s2));
else{
int result = Integer.parseInt(s1)-Integer.parseInt(s2);
Toast.makeText(getApplicationContext(), "더하기 빼기 결과는 "+result+"입니다",Toast.LENGTH_SHORT).show();
}

}
});

btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String s1 = e1.getText().toString();
String s2 = e2.getText().toString();

if(emptyCheck(s1,s2));
else{
int result = Integer.parseInt(s1)*Integer.parseInt(s2);
Toast.makeText(getApplicationContext(), "곱하기 계산 결과는 "+result+"입니다",Toast.LENGTH_SHORT).show();
}

}
});

btn4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String s1 = e1.getText().toString();
String s2 = e2.getText().toString();

if(emptyCheck(s1,s2));
else{
double result = (double)Integer.parseInt(s1)/Integer.parseInt(s2);
Toast.makeText(getApplicationContext(), "나누기 계산 결과는 "+result+"입니다",Toast.LENGTH_SHORT).show();
}

}
});

}
boolean isEmpty(String s){
return s == null || s.equals("");
}

boolean emptyCheck(String s1, String s2){
if(isEmpty(s1)){
Toast.makeText(getApplicationContext(),"값을 입력하세요.",Toast.LENGTH_SHORT).show();
e1.requestFocus();
return true;
}else if(isEmpty(s2)){
Toast.makeText(getApplicationContext(),"값을 입력하세요.",Toast.LENGTH_SHORT).show();
e2.requestFocus();
return true;
}
return false;
}

} 


실행화면입니다.





위의 모든 코드들은 깃허브(gitHub)에서 볼 수 있습니다!

https://github.com/Ywook/MyApplication2


안드로이드 스튜디오 기본 위젯(Widget)을 사용한 앱 만들기 (1)


이번 글에서는 기본 위젯(Widget)을 사용한 앱을 만들어 보겠습니다!


위젯 (Widget) 은 사용자와의 상호작용을 위한 인터페이스로 제공되는 뷰(View) 오브젝트를 말합니다.

다양한 기본 위젯(Widget)이 있지만 오늘은 TextView, EditText, Button, CheckBox를 사용해서 앱을 만들어보겠습니다.



먼저 프로젝트를 Empty Activity로 생성하고 res폴더 밑에 있는activity_main.xml파일에 가면 Hello World!로 써진 화면을 볼 수 있습니다.


왼쪽 밑에 있는 Text를 클릭하면 화면을 나타내고 있는 코드를 볼 수 있는데 

Layout을 나타내는 부분에 RelativeLayout 혹은 ConstraintLayout으로 적혀 있을텐데 이부분을 LinearLayout으로 변경합니다.

만약 ContrainLayout이였다면 TextView 안에 있는 app:layout_constraint~ 부분을 모두 지워줍니다.


그리고 android:orientation="vertical" 을 주면 위젯(Widget)이 위에서 아래로 추가되는 속성을 주는데 이것을 입력합니다.



Design 탭을 눌러서 다시 화면으로 돌아와서 왼쪽에 All, 혹은 Widgets를 클릭해서 나오는 Button을 클릭하고 아래와 같이 화면에 끌어옵니다!



총 5번을 반복하면 버튼 5개가 추가된 화면을 볼 수 있습니다.



Text탭을 눌러 다시 코드 화면으로 돌아오면 Button이 5개가 추가 된 코드를 볼 수 있습니다.


android:id="@+id/button"는 각 뷰(View)마다에서 구별할 수 있도록 id를 부여한다는 뜻입니다.

android:text=""""안에 글자를 입력하면 원하는 글자를 나타낼 수 있습니다.

android:layout_margin="" 를 통해 부모와 뷰(View) 4면의 간격을 동일하게 지정할 수 있으며

각 면에 개별적인 간격을 지정하고 싶으면 android:layout_marginTop="", android:layout_marginBottom="",

android:layout_marginLeft=""android:layout_marginRight="" 를 통해 지정할 수 있습니다.


저는 뷰가 딱 붙어있는게 마음에 들지 않아 android:layout_margin=""을 사용해서 약간의 간격을 주었습니다.


<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_margin="20dp"
android:layout_height="match_parent"
tools:context="examples.com.myapplication2.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="나의 첫번째 App"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="사과가격 계산" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="나이계산기" />

<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="온도변환" />

<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="레스토랑 주문" />

<Button
android:id="@+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="계산기" />

</LinearLayout> 


5개의 Activity를 더 생성해서 MainActivity에서 버튼이 눌리면 해당하는 Activity로 이동하게 설정하였습니다.

여기서 Intent는 Activity간에 이동을 하기 위해서 사용하는 것입니다.

첫번째 인자로 현재 액티비티 정보를 주고 두번째 인자로 호출할 액티비티의 Class를 설정해줍니다.

그리고 startActivity(intent)를 해주면 두번째 인자로 넣은 액티비티가 호출됩니다.


package examples.com.myapplication2;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
Button b1, b2, b3, b4, b5;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

init();

}

void init(){
b1 = (Button)findViewById(R.id.button);
b2 = (Button)findViewById(R.id.button2);
b3 = (Button)findViewById(R.id.button3);
b4 = (Button)findViewById(R.id.button4);
b5 = (Button)findViewById(R.id.button5);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
});

b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intent = new Intent(MainActivity.this, Main3Activity.class);
startActivity(intent);
}
});

b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intent = new Intent(MainActivity.this, Main4Activity.class);
startActivity(intent);
}
});

b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intent = new Intent(MainActivity.this, Main5Activity.class);
startActivity(intent);
}
});

b5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intent = new Intent(MainActivity.this, Main6Activity.class);
startActivity(intent);
}
});
}
}


실행화면입니다.

다음 글에서는 5개의 Activity를 작성해보겠습니다.




안드로이드 스튜디오 기본 위젯(Widget)을 사용한 앱 만들기 (2)


안드로이드 스튜디오 깃(GitHub) 연동하기


GitHub에 공유하고, 데이터를 받아오는 여러 가지 방법이 있습니다.


직접 명령어를 통해 GitHub를 사용하는 방법, GUI를 통한 방법, 안드로이드 스튜디오에서 제공하는 GitHub 공유 등 다양한 방법이 있습니다.


이 글에서는 안드로이드 스튜디오와 GitHub를 연동하는 방법을 작성하겠습니다.



새로운 프로젝트를 생성합니다.


상단 메뉴바의 오른쪽에 있는 VCS > Import into Version Control > Share Project on GitHub를 클릭합니다.





GitHub에 공유하기 위해서는 로그인을 해야 합니다. 만약 GitHub 계정이 없다면 밑에 Sign up을 클릭해서 회원가입을 합니다.

새로운 repository을 생성하는 부분인데 GitHub의 프로젝트 이름으로 나타납니다.

유로 사용자일 경우 Private 공유가 가능합니다.

GitHub에 공유하고 싶은 파일을 선택하고 OK 버튼을 클릭합니다.

아래와 같은 창이 표시될 수 있습니다. .idea/vcs.xml 파일이 추가로 생성되는데 이 파일을 업로드 해도 되고 안해도 되지만 저는 뭔가 올려아할 것 같아서 Yes를 눌렀습니다.



업로드가 완료되면 아래와 같은 창을 볼 수 있습니다.





GitHub에 들어가면 다음과 같이 프로젝트가 공유된 것을 확인 할 수 있습니다.





Push 하기



안드로이드 스튜디오 밑 부분에 있는 Version Control을 클릭하면 아래와 같은 창을 볼 수 있습니다.

Unversioned Files 아래에 있는 빨간색으로 표시되는 파일은 아직 git에 commit 할 수 없는 상태입니다.

Add를 해서 commit을 할 수 있는데 저 파일에서 마우스 오른쪽을 클릭해서 Add를 해줄 수 있습니다.


Default 아래에 있는 파일들은 Add는 되었지만 아직 commit은 안된 파일인데 마우스 오른쪽을 클릭해서 Commit Changes버튼을 클릭하면 Commit을 할 수 있습니다.





Commit할 파일들을 선택하고 Commit Message를 입력한 후에 우측하단에 있는 Commit버튼을 클릭하면 Commit이 완료됩니다.

Commit과 Push를 동시에 하고 싶으면 Commit and Push를 클릭하면 됩니다.


별도로 Push를 할 경우 VCS > Git > Push를 클릭하거나 맥에서는 Shift + command + K를 눌러주면 됩니다.



여러 건의 commit이 있다면 여러 건의 Message를 확인할 수 있습니다.

오른쪽 하단의 Push을 통해 Push가 진행됩니다.

Push가 완료되면 아래와 같은 창을 확인할 수 있습니다!


안드로이드 스튜디오 자기 이름 출력하는 앱 만들기



안드로이드 스튜디오를 실행하고 Start a new Android Studio project를 클릭합니다.

Application name은 앱의 이름을 지정합니다. 여기서 지정한 이름은 기본적으로 설치 및 실행되는 앱의 이름이 됩니다.

프로젝트 작성 중 언제든 변경할 수 있고 알파벳 대문자로 시작해야합니다. 예제에서는 "Post1"라고 했습니다.


Company domain은 개발자가 소속된 그룹이나 개발자 스스로를 식별할 수 있는 이름을 도메인 형식으로 입력하는 곳입니다.

예제에서는 "mobile.application"으로 했습니다.


Package name은 앱에 대한 고유 아이디로 사용됩니다. 앞에 입력한 "Company Domain"과 "Application name"을 조합하여 자동 생성됩니다.

안드로이드 스마트폰 또는 태블릿에서 동작하는 앱을 만들 것이므로 "Phone and Tablet"를 선택합니다.

"Phone and Table" 항목을 선택하면 "Minimum SDK"를 지정해야 합니다.  

"Minimum SDK"에서 지정하는 "API Level"은 앱이 실행될 최소의 안드로이드 버전을 의미합니다.

개발하고자 하는 앱의 요구사항이나 기능, 성능에 따라 적절히 선택해야하지만 간단한 앱을 만들 것이기 때문에 대부분 기기에서 사용가능한

API 16: Android 4.1 (Jelly Bean)을 선택하였습니다.

Empty Activity를 선택하고 Next를 클릭합니다.

프로젝트 생성의 마지막 단계로 Activity의 이름을 수정할 수 있는 화면이 표시됩니다. 

Activity Name을 수정해도 되지만 저는 그냥 finish를 클릭했습니다.

위의 사진과 동일한 Activity Name, Layout Name을 가진 프로젝트가 생성된 화면을 볼 수 있는데 res/layout폴더에 있는 activity_main.xml 파일을 더블 클릭해줍니다.

Hello World!가 출력되어 있는 화면을 볼 수 있는데 왼쪽 밑에 있는 Text를 클릭합니다.

android:text="Hello World!"의 ""사이에 출력하고 싶은 텍스트를 입력하면 작성한 텍스트로 출력이됩니다.

자기 이름 출력하는 앱 만들기이므로 Hello World!!!! 조영욱을 입력했습니다.

Design을 클릭해서 원래 화면으로 다시 돌아오면 Hello World!!!! 조영욱이 출력된 화면을 볼 수 있습니다.

만든 앱을 실행하기 위해서 안드로이드 스튜디오의 Run 'app' 메뉴를 클릭합니다.



앱을 실행할 기기 또는 에뮬레이터를 선택하는 화면이 출력되면, 기기를 선택하고 "OK" 버튼을 클릭합니다.

만약 연결되어 있는 기기 또는 에뮬레이터가 생성되어 있지 않다면 왼쪽 밑에 있는 Create New Emulator를 클릭해 새로운 에뮬레이터를

생성하고 진행합니다.

앱을 실행 후 잠시 기다리면 아래와 같이 앱이 실행된 화면이 표시되는 것을 확인할 수 있습니다!

위의 코드는  https://github.com/Ywook/Post1/blob/master/app/src/main/res/layout/activity_main.xml에서 확인할 수 있습니다!


+ Recent posts