[英]How to make phone calls programmatically in Android?
我在useful_numbers_item_fragment.xml中定義了以下布局:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/call_linear_layout">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/useful_nums_item_name"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/useful_nums_item_value"/>
</LinearLayout>
<ImageButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:src="@drawable/call"
android:id="@+id/call_btn"
android:onClick="callNumber"/>
</LinearLayout>
我在onCreate方法中動態填充一個名為UNItemListFragment.java的類中的兩個文本視圖:
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
if (getArguments().containsKey(Constants.UNItem.GROUP_ID)) {
simpleCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.useful_numbers_item_fragment, null,
new String[]{Constants.UNItem.NAME, Constants.UNItem.VALUE},
new int[]{R.id.useful_nums_item_name, R.id.useful_nums_item_value}, 0);
setListAdapter(simpleCursorAdapter);
getLoaderManager().initLoader(0, getArguments(), this);
}
}
對於每個號碼,如果我點擊按鈕,我想通過在用戶點擊按鈕時調用callNumber方法來打電話:
public void callNumber(View view) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
TextView unItemVal = (TextView) findViewById(R.id.useful_nums_item_value);
String phoneNumber = unItemVal.getText().toString();
callIntent.setData(Uri.parse("tel:" + phoneNumber));
startActivity(callIntent);
}
單擊列表中的第一個按鈕即可,但是當我單擊其他按鈕時,它會繼續調用第一行中定義的數字...
知道如何解決這個問題嗎?
問題是這一行:
TextView unItemVal = (TextView) findViewById(R.id.useful_nums_item_value);
在活動上執行,因此findViewById
將始終返回具有該id的第一個項目,這可能是列表中的第一個項目。
解決此問題的最佳方法是覆蓋適配器並將包含電話號碼的標簽添加到視圖中。 解決此問題的一種快速方法是在視圖層次結構中進行標記,如下所示:
public void callNumber(View view) {
if( view != null ) { // view is the button tapped
View parent = view.getParent(); // this should be the LinearLayout
if( parent instanceof LinearLayout ) {
TextView unItemVal = (TextView) ((LinearLayout)parent).findViewById(R.id.useful_nums_item_value);
if( unItemVal != null ) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String phoneNumber = unItemVal.getText().toString();
callIntent.setData(Uri.parse("tel:" + phoneNumber));
startActivity(callIntent);
}
}
}
}
這將找到單擊按鈕的父級,然后找到包含該ViewGroup
中的數字的文本視圖。
使用findViewById()
將返回具有指定id的活動或片段中的第一個視圖。 如果這是ListView,它將對應於第一行。
有很多方法可以解決這個問題。 最快的(但肯定不是最漂亮的,因為它取決於布局)將使用相對於包含列表項的LinearLayout的findViewById()
。 假設view
是ImageButton,它將是這樣的:
((View)view.getParent()).findViewById(R.id.useful_nums_item_value)
更優雅的解決方案是在適配器的getView()
設置一個標簽,其中包含您需要的數據(在這種情況下,是要調用的電話號碼)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.