I am new to Android Programming and I am making a simple browser in which I want to open my web activity by clicking the button but I am amazed to see that setOnClicklistener is not available in Android Studio 3.5 as I have just updated
3 Answers
Access/init Your button inside onCreate() method.
private Button btn; @Override public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); setContentView(R.layout.home_search_layout); btn = findViewById(R.id.someId); setClickListener(); } private void setClickListener() { btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } You need to put the setOnClickListener in one of the activity callbacks. In your onCreate() method, move the button there and then setOnClickListener().
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.filters); Button button = findViewById(R.id.google); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TODO() } }
} All the functional elements' code is to be initialized in the activity's onCreate() method. Since you want to make a button clickable, you need to add the setOnClickListener() in the onCreate() method, like so:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_selectionactivity); Button button = findViewById(R.id.google); //this id should be of a button not a view button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TODO do something } }
}I highlighted some text because from the image, you can see that the 9th that you get from the code completion menu is the setOnClickListener but the parent is from the group android.view.View but not from android.widget.Button. Make sure, that R.id.google is a Button and also put the code inside onCreate()