ดาวโหลด บทความ สถิติผู้ใช้ เกี่ยวกับเรา ติดต่อเรา
HomeAndroid

ทดลองทำแอพแรก

1. เปิด Android Studio เลือก New Project > Empty Activity
เลือก Android 4.1 และ Legacy Libraries แล้วกด Finish
2. ในแถบ Project เลือก App > res > layout > activity_main.xml คลิกแถบ Design
3. ลบ Hello World ออก



4. คลิกพื้นที่ว่างบนฟอร์ม แล้วดูแถบ Attributes ดูด้านล่างคลิก All Attributes ในช่อง Padding ให้ใส่ 16dp
5. ในช่อง Palette เลือก Text > Plain Text ลากลงในแบบฟอร์มของเรา
6. คลิกบน Text Box ที่เราเพิ่งสร้าง แล้วคลิกปุ่ม ไม้วิเศษ
7. คลิกขวาบน Text Box เลือกเมนู Center > Horizontally
8. คลิกขวาบน Text Box เลือกเมนู Organize > Expand Horizontally
9. คลิกบน Text Box แล้วดูแถบ Atrributes ในช่อง layout_width เลือก match_parent
10. เปลี่ยนช่อง ID เป็น txtName
11. ทำเหมือนข้อ 5 โดยลาก text box ใหม่ วางใต้ text box อันแรก แล้วทำตามข้อ 6 - 9
12. คลิกบน Text Box แล้วดูแถบ Atrributes ในช่อง text เปลี่ยนเป็น Password
เปลี่ยน ID เป้น txtPassword
13. ในช่อง Palette เลือก Common > Button ลากลงในแบบฟอร์มของเรา ใต้ txtPassword
14. คลิกบน Button ที่เราเพิ่งสร้าง แล้วคลิกปุ่ม ไม้วิเศษ
15. คลิกขวาบน Button เลือกเมนู Center > Horizontally

16. ในแถบ MainActivity.java ใส่ code นี้ ใน class ชื่อ MainActivity บรรทัดสุดท้ายก่อน }
public void go(View view) { }

จะได้ code หน้าตาตามนี้
package com.example.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    public void go(View view) {

    }
}
17. ในแถบ activity_main.xml คลิกปุ่ม button แล้วดูใน Attributes > Common Attributes > onClick เลือก Go
18. ในแถบ MainActivity.java แก้ code ตามนี้
    public void go(View view) {

        EditText txtName = findViewById(R.id.txtName);
        EditText txtPassword = findViewById(R.id.txtPassword);
        TextView output = findViewById(R.id.text1);

        int i1,i2;
        String u1, u2, u3;

        u1 = txtName.getText().toString();
        u2 = txtPassword.getText().toString();
        i1 = Integer.parseInt(u1) + Integer.parseInt(u2);

        u3 = String.valueOf(i1);

        output.setText(u3);
    }
19. ในช่อง Palette เลือก Common > TextView ลากลงในแบบฟอร์มของเรา ใต้ Button
20. คลิกบน Textbox ที่เราเพิ่งสร้าง แล้วคลิกปุ่ม ไม้วิเศษ
21. คลิกขวาบน Text Box เลือกเมนู Center > Horizontally
22. คลิกขวาบน Text Box เลือกเมนู Organize > Expand Horizontally
23. คลิกขวาบน Text Box เลือกเมนู Organize > Expand Vertically
24. เปลี่ยน ID เป็น text1
25. กด Run ได้เลย
26. กรอกช่อง Name ว่า 1111 ช่อง Password ว่า 2222 แล้วกด Button จะได้คำตอบเป็น 3333

29 ม.ค. 65
© 2000 - 2024 palthai.com. All rights reserved.