1. 程式人生 > >Android Studio入門小例子

Android Studio入門小例子

介面

activity_main.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:id="@+id/activity_main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context="com.example.zzyy.myapplication20161216.MainActivity"
    android:weightSum="1">

    <EditText
        android:id="@+id/myed"
        android:layout_width="188dp"
        android:layout_height="wrap_content"
        android:text="請輸入您的姓名"/>

    <Button
        android:id="@+id/mybut"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="顯示輸入資訊"/>



    <TextView
        android:id="@+id/mytext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="輸入的資訊是:"/>


</LinearLayout>


MainActivity.java

package com.example.zzyy.myapplication20161216;

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

public class MainActivity extends AppCompatActivity {

    private TextView showView = null;
    private EditText edit = null;
    private Button but = null;

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

        this.but = (Button)super.findViewById(R.id.mybut);
        this.showView = (TextView)super.findViewById(R.id.mytext);
        this.edit = (EditText)super.findViewById(R.id.myed);
        this.edit.setOnClickListener(new OnClickListenerImpl());
        this.edit.setOnFocusChangeListener(new OnFocusChangeListenerImpl());
        but.setOnClickListener(new ShowLIstener());

    }

    private class OnFocusChangeListenerImpl implements View.OnFocusChangeListener{
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(v.getId()==MainActivity.this.edit.getId()){
                if(hasFocus){
                    MainActivity.this.showView.setText("文字輸入 元件獲得焦點。");
                }else{
                    if(MainActivity.this.edit.getText().length()>0){

                    }else{
                        MainActivity.this.showView.setText("文字輸入元件失去焦點,輸入內容不能為空");
                    }
                }
            }
         }
    }

    private class OnClickListenerImpl implements View.OnClickListener{
        public void onClick(View v) {
            MainActivity.this.edit.setText("");
        }
    }

    private class ShowLIstener implements View.OnClickListener{
        public  void onClick(View view){
            String info = edit.getText().toString();
            showView.setText("輸入的內容是:"+info);
        }
    }
}


效果圖