Java 如何在Android中以编程方式拨打电话?
我在有用的\u numbers\u item\u fragment.xml中定义了以下布局:Java 如何在Android中以编程方式拨打电话?,java,android,android-intent,phone-call,Java,Android,Android Intent,Phone Call,我在有用的\u numbers\u item\u fragment.xml中定义了以下布局: <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:id="@+id/call_linear_lay
<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>
对于每个号码,如果我点击按钮,我想通过
当用户单击按钮时调用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的第一项,该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);
}
}
}
}
这将找到所单击按钮的父级,然后使用findViewById()查找包含该视图组中编号的文本视图。
将返回活动或片段中具有指定id的第一个视图。如果这是一个列表视图,它将对应于第一行
有很多方法可以解决这个问题。最快的(但肯定不是最漂亮的,因为它取决于布局)是相对于包含列表项的线性布局使用findviewbyd()
。假设view
是ImageButton,它将类似于:
((View)view.getParent()).findViewById(R.id.useful_nums_item_value)
一个更优雅的解决方案是在适配器的getView()
中设置一个标记,其中包含您需要的数据(在本例中,是要拨打的电话号码)
((View)view.getParent()).findViewById(R.id.useful_nums_item_value)