1. ホーム
  2. android

Android基本アプレット

2022-02-17 19:26:29

<スパン 1. シンプルなカウンター

xmlのレイアウトです。
アクティビティコードです。
public class MainActivity extends Activity {
    TextView tv;
    Button add,sub,reset;
    int count;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=(TextView) findViewById(R.id.tv); //associate the TextView in the xml file
        add=(Button)findViewById(R.id.add);
        sub=(Button)findViewById(R.id.sub);
        reset=(Button)findViewById(R.id.reset);
        count=0;
        add.setOnClickListener(new View.OnClickListener(){ //Add button listener
            @Override
            public void onClick(View v) {
                count++;
                tv.setText("The total is "+count);
            }
        });
        sub.setOnClickListener(new View.OnClickListener(){ //Sub button listener
            @Override
            public void onClick(View v) {
                count--;
                tv.setText("The total is "+count);
            }
        });
        reset.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                count=0;
                tv.setText("The total is 0");
            }
        });
    }
}



<スパン 2. スタート画面の実装

xmlレイアウト:まず、背景画像をres/drawableに追加し、次に
android:background="@drawable/filename(no suffix)"

アクティビティコードです。
public class flash extends Activity{
    MediaPlayer mp; //Reference to MediaPlay for music playback
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.flash);
        mp = MediaPlayer.create(this,R.raw.bgm); //Music files are stored in res/raw (if there is no raw folder, create it)
        mp.start(); //Music starts playing
        Thread timer = new Thread(){ //create a thread
            public void run(){
                try {
                    sleep(2000); //start interface exists for 2 seconds
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    Intent fl = new Intent("android.intent.action.MainMenu"); //use Intent to start the main interface Activity
                    startActivity(fl);
                }
            }

        };
        timer.start(); //thread start
    }

    @Override
    protected void onPause() { //Reference the onPause() method to end the current Activity
        super.onPause();
        mp.release(); //need to release, if this operation is not performed, it will continue to play until the end of the process
        finish(); //end this Activity
    }
}




<スパン 3. ListActivityを使用してリストメニューを作成する

レンダリング中です。


アクティビティコードです。
public class MainMenu extends ListActivity { //Inherits ListActivity
    //create an array of menu lists
    String classes[] = {"MainActivity","lifeActivity","TextPlay","Data","SharedPrefs"," quot;SimpleBrowser"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(MainMenu.this,android.R.layout.simple_list_item_1,classes));

    }
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) { //override the onListItemClick() method
        super.onListItemClick(l, v, position, id);
        String classStr = classes[position]; //record the order of the menu
        try {
            Class ourClass = Class.forName("com.example.jason.myapplication."+classStr);
            Intent startA = new Intent(this,ourClass); //class name of the way to specify the Activity to start
            startActivity(startA);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}




<スパン 4. シンプルなデザインのレイアウト

xmlレイアウトのコードとビュー。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="input text"
        android:ems="10"
        android:id="@+id/etCommand" />
<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:weightSum="100">
    <Button
        android:text="Try the command"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="20"
        android:id="@+id/btCommand" />

    <ToggleButton
        android:text="ToggleButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="80"
        android:id="@+id/tbStatus" />
</LinearLayout>
    <TextView
        android:text="TextView"
        android:textSize="30dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tvResult" />
</LinearLayout>


アクティビティコードです。
public class TextPlay extends Activity {
    EditText etCommand;
    ToggleButton tbStatus;
    Button btCommand;
    TextView tvResult;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text_play);
        etCommand = (EditText)findViewById(R.id.etCommand);
        tbStatus = (ToggleButton)findViewById(R.id.tbStatus);
        btCommand = (Button)findViewById(R.id.btCommand);
        tvResult = (TextView)findViewById(R.id.tvResult);
        btCommand.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                String check = etCommand.getText().toString();
                tvResult.setText(check);
                String color = tvResult.getTextColors().toString(); //get the font color in the TextView
                if(color.contentEquals("BLACK")==false){ //if the input font is "BLACK"
                    tvResult.setTextColor(Color.BLACK); //set the font color to black
                }
                if(check.contentEquals("left"){
                    tvResult.setGravity(Gravity.LEFT); //Set TextView to the left in the layout
                }else if(check.contentEquals("right")){
                    tvResult.setGravity(Gravity.RIGHT);
                }else if(check.contentEquals("center")){
                    tvResult.setGravity(Gravity.CENTER);
                }else if(check.contentEquals("blue")){
                    tvResult.setTextColor(Color.BLUE);
                }else if(check.contentEquals("yellow")){
                    tvResult.setTextColor(Color.YELLOW);
                }else if(check.contains("haha"){ //if the input font contains "haha"
                    Random crazyNum = new Random(); //define a random number
                    tvResult.setText("HAHA!!!! ");
                    tvResult.setTextSize(crazyNum.nextInt(100)); //Set a pseudo-random number of [0-100)
                    //use RGB to set random colors
                    tvResult.setTextColor(Color.rgb(crazyNum.nextInt(256),crazyNum.nextInt(256),crazyNum.nextInt(256))));
                    switch (crazyNum.nextInt(3)){
                        case 0:tvResult.setGravity(Gravity.LEFT);
                            break;
                        case 1:tvResult.setGravity(Gravity.RIGHT);
                            break;
                        case 2:tvResult.setGravity(Gravity.CENTER);
                            break;
                    }
                }else {
                    tvResult.setText("I can't recognize your command");
                }
            }
        });
        tbStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { //set the listen event for the switch button
                if(tbStatus.isChecked()){ //whether the button is turned on
                    //If it is, set it to password type input text
                    etCommand.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                }else {
                    //otherwise, set to text type
                    etCommand.setInputType(InputType.TYPE_CLASS_TEXT);
                }
            }
        });

    }
}


<スパン
5. アクティビティ通過文字

xmlレイアウトでは、以下のコードと効果で相対レイアウトを使用しています。
<スパン (a)


(b)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="How many people are there in our dormitory?"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tvQuestion"
        android:textSize="20dp"
        />

    <RadioGroup
        android:id="@+id/rgAnswers"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:text="four people"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/rbFour"
             />

        <RadioButton
            android:text="five people"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/rbFive"
             />

        <RadioButton
            android:text="six people"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/rbSix"
            />
    </RadioGroup>

    <Button
        android:text="Return"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bReturn" />

    <TextView
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tvOther" />
</LinearLayout>




アクティビティのコードです。
(a)
public class Data extends Activity implements View.OnClickListener {
    Button bsa,bsafr;
    EditText send;
    TextView tvGet;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.get);
        initialize(); //define a method for initializing
    }

    private void initialize() {
        bsa = (Button)findViewById(R.id.bSA);
        bsafr = (Button)findViewById(R.id.bSAFR);
        send = (EditText)findViewById(R.id.etSend);
        tvGet = (TextView)findViewById(R.id.get_tv);
        bsa.setOnClickListener(this); // use the implementation of the interface to listen for clicks
        bsafr.setOnClickListener(this);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){ //Get the ID of the button
            case R.id.bSA:
                String s = send.getText().toString(); //Get the character to be sent
                Bundle basket = new Bundle(); //create a bundle
                basket.putString("breakfast",s); //bundle with a string in it
                Intent it = new Intent(this,OpenedClass.class); //use Intent to jump to the Activity named OpenedClass
                it.putExtras(basket); //use the putExtras method and pass a bundle
                startActivity(it); //open OpenedClassActivity
                break;
            case R.id.bSAFR:
                String b = send.getText().toString();//same as above
                Bundle ket = new Bundle();
                ket.putString("breakfast",b);
                Intent i = new Intent(this,OpenedClass.class);
                i.putExtras(ket);
                startActivityForResult(i,0); //Activity return string
                break;

        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { //rewrite the onActivityResult method after the return
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            Bundle answer = data.getExtras(); //Get the returned bundle
            String s = answer.getString("answer"); //get the string from bundle
            tvGet.setText(s); //set to TextView
        }


    }
}


(b)
public class OpenedClass extends Activity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {
    RadioGroup selectionList;
    Button bReturn;
    TextView question,other;
    String s;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send);
        initialize();
    }

    private void initialize() {
        selectionList = (RadioGroup)findViewById(R.id.rgAnswers);
        bReturn = (Button)findViewById(R.id.bReturn);
        question = (TextView)findViewById(R.id.tvQuestion);
        other = (TextView)findViewById(R.id.tvOther);
        selectionList.setOnCheckedChangeListener(this);
        bReturn.setOnClickListener(this);

        Bundle basket = getIntent().getExtras(); //receive the bundle passed by the previous Activity
        String q = basket.getString("breakfast"); //get the string in the bundle
        question.setText(q); //show to TextView
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) { //Listen for changes in RadioGroup
        switch (checkedId){ //select based on RadioButton's ID
            case R.id.rbFour:
                s = "four people";
                break;
            case R.id.rbFive:
                s = "five people";
                break;
            case R.id.rbSix:
                s = "six people";
                break;
        }
        other.setText(s); //show to TextView
    }

    @Override
    public void onClick(View v) { //Return button's click listener
        Intent answer = new Intent();
        Bundle ket = new Bundle();
        ket.putString("answer",s);
        answer.putExtras(ket); // send the characters bound in the bundle using the Intent's putExtras method as usual
        setResult(RESULT_OK,answer); //set the return message
        finish(); //end the current Activity
    }
}




6. SharedPreferencesはデータを保存する

xmlレイアウトのコードです。


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/etSave" />

    <Button
        android:text="Save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bSave" />

    <Button
        android:text="Load"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bLoad" />

    <TextView
        android:text="Load your data"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tvLoad" />
</LinearLayout>

アクティビティのコードです。
public class SharedPrefs extends Activity implements View.
    Button save,load;
    TextView show;
    EditText input;
    SharedPreferences someData; //define a SharedPreferences
    public static String filename = "MySharedString"; //define a static storage name
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sharedpreferences);
        setupVariables();
        someData = getSharedPreferences(filename,0); //get the data in sharedPreferences (whether it exists or not)
    }

    private void setupVariables() {
        save = (Button)findViewById(R.id.bSave);
        load = (Button)findViewById(R.id.bLoad);
        show = (TextView)findViewById(R.id.tvLoad);
        input = (EditText)findViewById(R.id.etSave);

        save.setOnClickListener(this);
        load.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bSave:
                String sharedString = input.getText().toString();
                Editor editor = someData.edit(); //define editor for changing data
                editor.putString("sharedString",sharedString); //put the data
                editor.commit(); //execute commit commit
                break;
            case R.id.bLoad:
                //Get the data whose key is sharedString, if exception, then display Not get
                String getString = someData.getString("sharedString","Not get");
                show.setText(getString); //show to TextView
                break;
        }
    }
}




<スパン 7. WebViewでウェブをブラウズする

xmlのコードです。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="100"
    >
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="20"
        android:inputType="textPersonName"
        android:id="@+id/etSite" />

    <Button
        android:text="Go"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="80"
        android:id="@+id/bGo" />
</LinearLayout>
    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/wvShow"/>
</LinearLayout>

アクティビティのコードです。
public class SimpleBrowser extends Activity implements View.OnClickListener {
    //In addition add network permissions to mainifests<uses-permission android:name="android.permission.INTERNET"/> //add network permissions
    Button go;
    EditText site;
    WebView webShow;
    @Override
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simplebrowser);
        go = (Button)findViewById(R.id.bGo);
        site = (EditText)findViewById(R.id.etSite);
        webShow = (WebView)findViewById(R.id.wvShow);
        go.setOnClickListener(this);

        webShow.loadUrl("http://www.baidu.com"); //login to Baidu webpage
        webShow.setWebViewClient(new OurClient()); //Set the override to browse the jump page (jump does not call the system browser to open)

        //adapt the screen when opening the page
        webShow.getSettings().setLoadWithOverviewMode(true);
        webShow.getSettings().setUseWideViewPort(true);//set this property to scale to any ratio
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bGo:
                String loadSite = site.getText().toString();
                webShow.loadUrl(loadSite);
                break;
        }
    }

    private class OurClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) { //underline to prove that this method is obsolete
            view.loadUrl(url);
            return true;
        }
    }
}