筆者正在自學(xué)Android開(kāi)發(fā),隨著學(xué)習(xí)的進(jìn)程的加深,我會(huì)寫(xiě)一些小白級(jí)別的案例,一是為了保存代碼和筆記,二也是為了供同樣熱愛(ài)Android的小伙伴參考。這里寫(xiě)了一個(gè)小案例,叫電話(huà)撥號(hào)器。下面詳細(xì)介紹如何做:
對(duì)于我們初學(xué)者來(lái)說(shuō),做案例不同于做項(xiàng)目,我們是為了學(xué)習(xí)所以做案例基本上就是以下三步:
1、做界面UI
2、做業(yè)務(wù)邏輯,就是具體的編程實(shí)現(xiàn)
3、做測(cè)試,可以用模擬器,也可用真機(jī)。(這里說(shuō)一下,如果你的電腦配置不是很高,但有Android的真機(jī)的話(huà),用真機(jī)吧,模擬器真的是太慢了)
首先,做UI,大概是醬紫的:

這個(gè)很簡(jiǎn)單了,需要添加三個(gè)控件“Text View”“Edit Text”“Button”,再加一個(gè)布局,布局可以自己選我用的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>
這里說(shuō)一下,match_parent與wrap_content 的區(qū)別和Text View中如何設(shè)置字體的大小。
match_parent的布局是填充的意思就是無(wú)論字?jǐn)?shù)夠不夠,都會(huì)去填充到最大,效果就像上圖Button的長(zhǎng)一樣,而wrap_content是自適應(yīng)大小,就是你要多少是多少。
Text View中字體大小的設(shè)置用textSize屬性,上述代碼中的“@dimen/textsize”其實(shí)在values的dimens.xml中是“19sp”。
然后是做業(yè)務(wù)邏輯,那要做業(yè)務(wù)邏輯就要明白我們想要實(shí)現(xiàn)啥功能。從大的方面看,我們要實(shí)現(xiàn)打電話(huà)的功能。那我們細(xì)分一下邏輯流程,首先我們?cè)谖谋究騼?nèi)輸入號(hào)碼,然后我們點(diǎn)擊按鈕就可以撥通電話(huà),大概就是這樣的過(guò)程。那我們是不是先要取到輸入的號(hào)碼,我們可以讓點(diǎn)擊Button的時(shí)候取數(shù)據(jù),然后進(jìn)行與電話(huà)關(guān)聯(lián),來(lái)打電話(huà)。那這樣我們就清楚了,我們需要做的是:
1、為button添加點(diǎn)擊事件
2、取到輸入的字符串
3、為Intent對(duì)象設(shè)置CALL動(dòng)作和數(shù)據(jù)
4、加上打電話(huà)的權(quán)限
下面是代碼展示:
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添加點(diǎn)擊事件 btn_call.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //取數(shù)據(jù) String number= MainActivity.this.et_call.getText().toString().trim();//trim()方法用來(lái)去掉空格 if("".equals(number)) { //土司,提示 Toast mes = Toast.makeText(MainActivity.this, "對(duì)不起,輸入不能為空", Toast.LENGTH_LONG); mes.show(); } //Intent設(shè)置動(dòng)作和數(shù)據(jù) Intent intent=new Intent(); intent.setAction(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:"+number)); startActivity(intent); } }); }}記得加權(quán)限不然會(huì)報(bào)錯(cuò):

最后是測(cè)試,我用的是真機(jī)測(cè)試的。模擬器太慢,真機(jī)要快很多。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注