第一步、布局文件
<?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="horizontal"> <LinearLayout android:layout_width="150dp" android:layout_height="40dp"> <TextView android:id="@+id/num_desc_textview" android:layout_width="45dp" android:layout_height="match_parent" android:layout_gravity="left" android:background="@drawable/jian" android:gravity="center" android:padding="10dp" /> <EditText android:id="@+id/num_textview" android:layout_width="60dp" android:layout_height="match_parent" android:layout_gravity="center_horizontal" android:background="@drawable/shuzi" android:gravity="center" android:inputType="number" android:padding="10dp" android:singleLine="true" android:text="0" /> <TextView android:id="@+id/num_add_textview" android:layout_width="45dp" android:layout_height="match_parent" android:layout_gravity="right" android:background="@drawable/jia" android:gravity="center" android:padding="10dp" /> </LinearLayout> </LinearLayout>
package com.bruce.testaddview; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity implements View.OnClickListener { private TextView mDescTextView, mAddTextView; private EditText mNumEdit; private int num = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mains); mDescTextView = (TextView) findViewById(R.id.num_desc_textview); mAddTextView = (TextView) findViewById(R.id.num_add_textview); mNumEdit = (EditText) findViewById(R.id.num_textview); mDescTextView.setOnClickListener(this); mAddTextView.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub String str = mNumEdit.getText().toString(); if (str == null || "".equals(str)) { num = 0; } else { num = Integer.parseInt(str); } switch (v.getId()) { case R.id.num_add_textview: num++; mNumEdit.setText(String.valueOf(num)); break; case R.id.num_desc_textview: num--; if (num <= 0) { num = 0; } mNumEdit.setText(String.valueOf(num)); break; } num = Integer.parseInt(mNumEdit.getText().toString()); Log.w("tag", "<>" + num); } }