您的位置:首页 > 移动开发 > Android开发

android布局与计算器app编程

2016-07-07 19:14 267 查看
android布局分为:

1.线性布局LinearLayout

2.相对布局RelativeLayout

3.绝对布局AbsoluteLayout

4.帧布局FrameLayout

5.表格布局TableLayout

线性布局LinearLayout比较简单,元素可以水平顺序排放,也可以垂直顺序排放,元素内部也可以设置线性布局进行嵌套布局设置。

我的计算器app就是使用了嵌套线性布局来完成的。

代码如下:

<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"
tools:context=".MainActivity"
android:orientation="vertical"
>

<EditText
android:inputType="text"
android:id="@+id/num_input"
android:layout_width="match_parent"
android:layout_height="80dp"
/>

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

<Button
android:text="@string/one"
android:id="@+id/one"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="match_parent"
android:background="#00FF00"
/>
<Button
android:text="@string/two"
android:id="@+id/two"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="match_parent"
android:background="#00FF00"
/>
<Button
android:text="@string/three"
android:id="@+id/three"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="match_parent"
android:background="#00FF00"
/>
<Button
android:text="@string/cheng"
android:id="@+id/jia"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="match_parent"
android:background="#00FF00"
/>
</LinearLayout>
</LinearLayout>


这里只给出了一个输入框与一排按钮的代码,还有三排代码是重复的,参考嵌套布局。

界面布局设置好了之后,往按钮加上监听,然后别写计算代码就可以了。

监听与计算代码如下:

OnClickListener click = new OnClickListener(){
@Override
public void onClick(View v) {
Button bt = (Button)v;
inContent = inContent + bt.getText();
EditText et = (EditText) findViewById(R.id.num_input);
et.setText(inContent);
}
};
public void in_guiling(View v){
inContent = "";
EditText et = (EditText) findViewById(R.id.num_input);
et.setText(inContent);
}
public void in_result(View v){
int count = 0;
char c = 0;
int pre = 0;
int last = 0;
while(count < inContent.length()){
if( inContent.charAt(count) == '+'||
inContent.charAt(count) == '-'||
inContent.charAt(count) == '*'||
inContent.charAt(count) == '/'
){
c = inContent.charAt(count);
pre = Integer.parseInt(inContent.substring(0, count));
last = Integer.parseInt(inContent.substring(count+1));
}
count ++;
}
int value = 0;
switch(c){
case'+':value = pre+last;break;
case'-':value = pre-last;break;
case'*':value = pre*last;break;
case'/':value = pre/last;break;
}
String sss = Integer.toString(value);
EditText et = (EditText) findViewById(R.id.num_input);
et.setText(sss);
}


我的app是这样的:



颜色是测试布局的时候加上去的,后来发现把颜色去掉的话就太沉闷了,所以就不修改了。
测试结果:



相对布局RelativeLayout比LinearLayout要灵活,可以根据前后组件的位置来调动自己的位置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: