本文共 2682 字,大约阅读时间需要 8 分钟。
一个一个组件的实习过来。
package com.tw.flag.ch02_button;import android.content.Context;import android.graphics.Color;import android.os.Bundle;import android.os.Vibrator;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.text.Editable;import android.text.TextWatcher;import android.view.MotionEvent;import android.view.View;import android.view.Menu;import android.view.MenuItem;import android.widget.Button;import android.widget.EditText;import android.widget.RadioGroup;import android.widget.TextView;import java.util.Random;public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, TextWatcher{ RadioGroup unit; EditText value; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); unit = (RadioGroup) findViewById(R.id.unit); unit.setOnCheckedChangeListener(this); value = (EditText) findViewById(R.id.value); value.addTextChangedListener(this); } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { calc(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { calc(); } protected void calc() { TextView degF = (TextView)findViewById(R.id.degF); TextView degC = (TextView)findViewById(R.id.degC); double f, c; if (unit.getCheckedRadioButtonId() == R.id.unitF) { f = Double.parseDouble(value.getText().toString()); c = (f - 32) * 5/9; } else { c = Double.parseDouble(value.getText().toString()); f = c * 9/5 + 32; } degC.setText(String.format("%.1f", c) + getResources().getString(R.string.charC)); degF.setText(String.format("%.1f", f) + getResources().getString(R.string.charF)); }}
转载地址:http://gzfwl.baihongyu.com/