Reputation: 19
I have a search button in my main activity "btnSearch", whenevr I press this button I want it to take me to a new activity "search", here's the Java code that I have for this:
public class MainMenu extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
Button btnSearch= (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(listener);
View.OnClickListener listener=new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(), Search.class);
startActivity(intent);
}
};
}
}
in the btnSearch.setOnClickListener(listener);
. it gives me the error: Cannot resolve symbol 'listner'.
What should I do?
Upvotes: 0
Views: 593
Reputation: 28298
You declare the listener inside onCreate, which means it's only accessible after you initialize it. Move btnSearch.setOnClickListener
after you create the listener, or move the listener declaration to the class level.
Alternatively, you can skip creating a variable entirely and just pass the listener directly:
btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Search.class);
startActivity(intent);
}
});
Upvotes: 3