MainActivity.java
«`java
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText nameEditText;
EditText phoneEditText;
Button addButton;
ListView contactsListView;
ArrayList
ArrayAdapter
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameEditText = findViewById(R.id.nameEditText);
phoneEditText = findViewById(R.id.phoneEditText);
addButton = findViewById(R.id.addButton);
contactsListView = findViewById(R.id.contactsListView);
contacts = new ArrayList<>();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, contacts);
contactsListView.setAdapter(adapter);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = nameEditText.getText().toString();
String phone = phoneEditText.getText().toString();
if (name.isEmpty() || phone.isEmpty()) {
return;
}
contacts.add(name + «: » + phone);
adapter.notifyDataSetChanged();
nameEditText.setText(«»);
phoneEditText.setText(«»);
}
});
}
}
«`
activity_main.xml
«`xml
«`