项目要求:
设置一个手机拨号界面如下:
<img src="https://img-blog.youkuaiyun.com/20141107010034401?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3Rsc3Q=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">1.button的事件监听函数</span>
private OnClickListener b_listener = newOnClickListener(){
public void onClick(View v) {
if (v == btn[12]){//如果按键是“回删”
if(!text.isEmpty()){//且当前文本不为空
text = text.substring(0, text.length()-1);//将字符串的最后一位删除
number.setText(text);
}
}
else{//如果是其他非“回删”按键,则直接把按键的文本值加到当前text的末端
Button temp = (Button)v;
text = text + temp.getText();
number.setText(text);
}
}
};
2.定义四个线性布局
for(inti = 0;i<4;i++){//用一个for循环定义4个LinearLayout
l[i] = new LinearLayout(this);
l[i].setOrientation(LinearLayout.HORIZONTAL);//每个LinearLayout里面是水平排列控件的
mLinearLayout.addView(l[i]);//把每个Linearlayout嵌套加入主布局mLinearLayout中
}
3.定义10个数字按钮以及“ * ”, “ # ”
LinearLayout.LayoutParamscontentLayoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);//定义控件的权重参数
contentLayoutParams.weight = 1;//设定权重为1
for(int i = 0;i<4;i++){//外层循环代表四个LinearLayout
for(int j = 0;j<3;j++){//内层循环代表每个Linearlayout里的三个Button
btn[i*3+j] = new Button(this);
if(i*3+j == 9)
btn[i*3+j].setText("*");
else if(i*3+j == 10)
btn[i*3+j].setText("0");
else if(i*3+j == 11)
btn[i*3+j].setText("#");
else
btn[i*3+j].setText(i*3+j+1+"");
l[i].addView(btn[i*3+j],contentLayoutParams);//把每个Button加上权重放入当前Linearlayout布局中
}
}
4.为Button数组绑定监听器OnClickListener
for(Button button : btn){//遍历整个Button数组,为它们共同定义一个监听器b_listener
button.setOnClickListener(b_listener);
}
points:
1.对功能相似的Button的OnClickListener进行批量处理。对Button数组绑定同一个监听器的方法,对代码的长度进行了比较大限度的优化。
2.批量定义Button,Linearlayout。
3.对按钮设置权重,使其均匀分布。