MVC设计模式及Menu之简易计算器

一.学习目标

1. 掌握UI界面的嵌套布局

2. EditText通过三种属性可以指定

    android:digits   数字 0~9 或字母 a~z

    android:inputType自定义输入的类型

    android:numeric 数字类型

3. 掌握MVC设计模式的运用

4.掌握Menu组件的使用

5. AlertDialog.Builder对话框的使用

二.任务描述

实现简易计算器的功能,当除数为0是给出相应提示,当点击menu时显示出菜单,并完成菜单的相应功能

三.编写过程

1.阶段一界面布局

使用LinearLayout进行页面嵌套布局

布局代码如下:

<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="vertical" 最外层布局采用垂直方向的布局
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="@drawable/pg" >
最外层之下嵌套两个LinearLayout,每个LinearLayout都采用水平方向的布局
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/op1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"  用此属性来使此LinearLayout中的三个控件平均分配,分别占五分之一
            android:inputType="numberDecimal" >
        </EditText>

        <TextView
            android:id="@+id/op"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" >
        </TextView>

        <EditText
            android:id="@+id/op2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="numberDecimal" >
        </EditText>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="=" >
        </TextView>

        <TextView
            android:id="@+id/result"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" >
        </TextView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="+" >
        </Button>

        <Button
            android:id="@+id/sub"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="-" >
        </Button>

        <Button
            android:id="@+id/multiply"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="*" >
        </Button>
        <Button
            android:id="@+id/divid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="/" >
        </Button>
    </LinearLayout>
</LinearLayout>
界面布局效果如下:

2.阶段二

在Mainactivity中编写代码,利用MVC设计模式吧模型,显示界面和控制器分开,因此要编写相应的Java类。计算器的计算功能抽取出来,代码如下

public class Op {
 public static double add(double num1,double num2){
	 return num1+num2;
 }
 public static double sub(double num1,double num2){
	 return num1-num2;
 }
 public static double multiply(double num1,double num2){
	 return num1*num2;
 }
 public static double divid(double num1,double num2) throws ArithmeticException{ 
	 return num1/num2;
 }
	

}
具体的计算实现功能和菜单功能在Mainactivity中实现,代码如下:
public class MainActivity extends Activity {
	private EditText op1Text;
	private EditText op2Text;
	private TextView opText;
	private TextView resultText;
	private Button add;
	private Button sub;
	private Button multiply;
	private Button divid;
	
	

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Init();
        
    }
   private void Init(){
		op1Text=(EditText)findViewById(R.id.op1);
		
		opText=(TextView)findViewById(R.id.op);
		op2Text=(EditText)findViewById(R.id.op2);
		resultText=(TextView)findViewById(R.id.result);
		opHander handle=new opHander();
		add=(Button)findViewById(R.id.add);
		add.setOnClickListener(handle);
		sub=(Button)findViewById(R.id.sub);
		sub.setOnClickListener(handle);
		multiply=(Button)findViewById(R.id.multiply);
		multiply.setOnClickListener(handle);
		divid=(Button)findViewById(R.id.divid);
		divid.setOnClickListener(handle);
		
	}
    private class opHander implements  OnClickListener{
    	@Override
    	public void onClick(View v) {
			String op1Str=op1Text.getText().toString();
			String op2Str=op2Text.getText().toString();
			double num1=Double.parseDouble(op1Str);
			double num2=Double.parseDouble(op2Str);
			double result=0;
			switch (v.getId()) {
			case R.id.add:
				opText.setText(" + ");
                result=Op.add(num1, num2);
				break;
			case R.id.sub:
				opText.setText(" - ");
                result=Op.sub(num1, num2);
				break;
			case R.id.multiply:
				opText.setText(" * ");
                result=Op.multiply(num1, num2);
				break;
			case R.id.divid:
				opText.setText(" / ");
                if(num2==0){
                	resultText.setText("除数不能为0");
                    Toast.makeText(MainActivity.this, "除数不能为0", Toast.LENGTH_LONG).show();
                }
                else
                    result=Op.divid(num1, num2);
				break;
			default:
				break;
			}
			
			if(!(num2==0&&" / ".equals(opText.getText())))
			    resultText.setText(""+result);

		}
	}

	


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
    	
        return true;
    }
    @Override
//实现菜单中的对话框功能	
    public boolean onOptionsItemSelected(MenuItem item){
    	switch(item.getItemId()){
    	case R.id.about:
    		AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(R.string.about)
			       .setMessage("计算器\n作者:xxx")
			       .setPositiveButton("确定", new DialogInterface.OnClickListener() {
			    	   public void onClick(DialogInterface dialog, int which) {
			    		   
			    	   }
			       }) 
			    	   .create()
					   .show();
								
    					break;
    	case R.id.exit:
    		this.finish();
		default:
			break;
    	 
    	}
		return super.onOptionsItemSelected(item);
    }
}
    	


 

四.程序运行效果

 

 


 


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MVC模式是一种经典的设计模式,它将系统分为三个部分:模型(Model)、视图(View)和控制器(Controller),以实现系统的解耦和可维护性。 在简易点餐系统中,我们可以将模型定义为数据模型,视图定义为界面,控制器定义为业务逻辑。 1. 数据模型(Model) 数据模型包含系统中的所有数据,例如菜单,订单,用户等。它负责管理数据的存储、读取和更新。可以使用关系型数据库或非关系型数据库来实现数据模型。 2. 界面(View) 界面是系统的用户界面,它负责展示数据和接收用户的操作。在简易点餐系统中,可以设计一个简单的界面,包含菜单列表、购物车和结算功能。 3. 业务逻辑(Controller) 业务逻辑是系统的核心,它负责处理用户的操作,包括浏览菜单、添加菜品到购物车、修改购物车中的菜品、下单等。在简易点餐系统中,可以设计一个控制器来处理这些操作,并将结果返回给界面。 下面是一个简单的实现: 模型(Model): ``` class MenuItem: def __init__(self, name, price): self.name = name self.price = price class OrderItem: def __init__(self, menu_item, quantity): self.menu_item = menu_item self.quantity = quantity class Order: def __init__(self): self.items = [] def add_item(self, menu_item, quantity): self.items.append(OrderItem(menu_item, quantity)) def remove_item(self, index): del self.items[index] def total_price(self): return sum(item.menu_item.price * item.quantity for item in self.items) ``` 界面(View): ``` class MenuView: def __init__(self, menu_items): self.menu_items = menu_items def display_menu(self): for i, item in enumerate(self.menu_items): print(f"{i + 1}. {item.name}: ${item.price}") class OrderView: def __init__(self, order): self.order = order def display_order(self): for i, item in enumerate(self.order.items): print(f"{i + 1}. {item.menu_item.name} x {item.quantity}: ${item.menu_item.price * item.quantity}") print(f"Total: ${self.order.total_price()}") class CheckoutView: def __init__(self, order): self.order = order def display_checkout(self): print("Thank you for your order!") print("Your order:") OrderView(self.order).display_order() ``` 控制器(Controller): ``` class MenuController: def __init__(self, menu_items): self.menu_items = menu_items self.view = MenuView(menu_items) def display_menu(self): self.view.display_menu() class OrderController: def __init__(self, order): self.order = order self.view = OrderView(order) def add_item(self, menu_item, quantity): self.order.add_item(menu_item, quantity) self.view.display_order() def remove_item(self, index): self.order.remove_item(index) self.view.display_order() class CheckoutController: def __init__(self, order): self.order = order self.view = CheckoutView(order) def checkout(self): self.view.display_checkout() ``` 使用示例: ``` if __name__ == "__main__": # 初始化菜单 menu_items = [MenuItem("Hamburger", 5), MenuItem("Fries", 2), MenuItem("Soda", 1)] # 初始化订单 order = Order() # 显示菜单 menu_controller = MenuController(menu_items) menu_controller.display_menu() # 添加菜品到购物车 order_controller = OrderController(order) order_controller.add_item(menu_items[0], 2) order_controller.add_item(menu_items[1], 1) order_controller.add_item(menu_items[2], 3) # 修改购物车中的菜品 order_controller.remove_item(0) # 结算订单 checkout_controller = CheckoutController(order) checkout_controller.checkout() ``` 这就是一个简单的基于MVC设计模式的点餐系统的实现。它将系统的不同部分分离开来,使得系统更易于维护和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值