Skip to content Skip to sidebar Skip to footer

How To Make Phone Calls Programmatically In Android?

I have the following layout defined in useful_numbers_item_fragment.xml: Copy

is executed on the activity, so the findViewById will always return the first item with that id, which is likely the first item in the list.

The best way to fix this would be to override the adapter and add a tag containing the phone number to the view. A quick way to fix this would be to tag along in the view hierarchy, like so:

publicvoidcallNumber(View view) {
    if( view != null ) { // view is the button tappedViewparent= view.getParent(); // this should be the LinearLayoutif( parent instanceof LinearLayout ) {
            TextViewunItemVal= (TextView) ((LinearLayout)parent).findViewById(R.id.useful_nums_item_value);
            if( unItemVal != null ) {
                IntentcallIntent=newIntent(Intent.ACTION_CALL);
                StringphoneNumber= unItemVal.getText().toString();
                callIntent.setData(Uri.parse("tel:" + phoneNumber));
                startActivity(callIntent);
            }
        }
    }
}

This would find the parent for the button that was clicked, and then find the text-view containing the number within that ViewGroup.

Solution 2:

Using findViewById() will return the first view in the activity or fragment with the specified id. If this is a ListView, it will correspond to the first row.

There are many ways to work around this problem. The quickest one (but certainly not the prettiest one, since it depends on the layout) would be to use findViewById() relative to the LinearLayout that contains the list item. Assuming that view is the ImageButton, it would be somthing like:

((View)view.getParent()).findViewById(R.id.useful_nums_item_value)

A more elegant solution would be to set a tag in the adapter's getView(), containing the data you need (in this case, the phone number to call).

Post a Comment for "How To Make Phone Calls Programmatically In Android?"