Android電話撥號器實例詳解
筆者正在自學Android開發(fā),隨著學習的進程的加深,我會寫一些小白級別的案例,一是為了保存代碼和筆記,二也是為了供同樣熱愛Android的小伙伴參考。這里寫了一個小案例,叫電話撥號器。下面詳細介紹如何做:
對于我們初學者來說,做案例不同于做項目,我們是為了學習所以做案例基本上就是以下三步:
1、做界面UI
2、做業(yè)務邏輯,就是具體的編程實現(xiàn)
3、做測試,可以用模擬器,也可用真機。(這里說一下,如果你的電腦配置不是很高,但有Android的真機的話,用真機吧,模擬器真的是太慢了)
首先,做UI,大概是醬紫的:
這個很簡單了,需要添加三個控件“Text View”“Edit Text”“Button”,再加一個布局,布局可以自己選我用的LinearLayout。
<LinearLayout android:layout_width="368dp" android:layout_height="495dp" android:layout_marginTop="8dp" android:orientation="vertical" android:visibility="visible" app:layout_constraintTop_toTopOf="parent" tools:layout_editor_absoluteX="8dp"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:textSize="@dimen/textsize" android:layout_height="wrap_content" android:text="@string/text_1" /> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="number" /> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/text_2" /> </LinearLayout>
這里說一下,match_parent與wrap_content 的區(qū)別和Text View中如何設置字體的大小。
match_parent的布局是填充的意思就是無論字數(shù)夠不夠,都會去填充到最大,效果就像上圖Button的長一樣,而wrap_content是自適應大小,就是你要多少是多少。
Text View中字體大小的設置用textSize屬性,上述代碼中的“@dimen/textsize”其實在values的dimens.xml中是“19sp”。
然后是做業(yè)務邏輯,那要做業(yè)務邏輯就要明白我們想要實現(xiàn)啥功能。從大的方面看,我們要實現(xiàn)打電話的功能。那我們細分一下邏輯流程,首先我們在文本框內輸入號碼,然后我們點擊按鈕就可以撥通電話,大概就是這樣的過程。那我們是不是先要取到輸入的號碼,我們可以讓點擊Button的時候取數(shù)據(jù),然后進行與電話關聯(lián),來打電話。那這樣我們就清楚了,我們需要做的是:
1、為button添加點擊事件
2、取到輸入的字符串
3、為Intent對象設置CALL動作和數(shù)據(jù)
4、加上打電話的權限
下面是代碼展示:
public class MainActivity extends AppCompatActivity { private Button btn_call; private EditText et_call; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_call=(EditText) findViewById(R.id.editText); btn_call=(Button)findViewById(R.id.button); //為button添加點擊事件 btn_call.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //取數(shù)據(jù) String number= MainActivity.this.et_call.getText().toString().trim();//trim()方法用來去掉空格 if("".equals(number)) { //土司,提示 Toast mes = Toast.makeText(MainActivity.this, "對不起,輸入不能為空", Toast.LENGTH_LONG); mes.show(); } //Intent設置動作和數(shù)據(jù) Intent intent=new Intent(); intent.setAction(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:"+number)); startActivity(intent); } }); } }
記得加權限不然會報錯:
最后是測試,我用的是真機測試的。模擬器太慢,真機要快很多。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android中TextView文本高亮和點擊行為的封裝方法
這篇文章主要介紹了Android中TextView文本高亮和點擊行為的封裝方法,文中介紹的非常詳細,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-03-03Android動態(tài)修改ToolBar的Menu菜單示例
本篇文章主要介紹了Android動態(tài)修改ToolBar的Menu菜單示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02另外兩種Android沉浸式狀態(tài)欄實現(xiàn)思路
這篇文章主要為大家介紹了另外兩種Android沉浸式狀態(tài)欄實現(xiàn)思路,android5.0及以后版本都支持給狀態(tài)欄著色,而目前android主流版本還是4.4,想要深入了解的朋友可以參考一下2016-01-01