So I have done some research, and after defining you button as an object by the code
private Button buttonname;
buttonname = (Button) findViewById(R.id.buttonnameinandroid) ;
here is my problem
buttonname.setOnClickListener(this); //as I understand it, the "**this**" denotes the current `view(focus)` in the android program
then your OnClick()
event...
Problem:
When I type in the "this", it says:
setOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)
I have no idea why?
here is the code from the .java file
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private Button btnClick;
private EditText Name, Date;
private TextView msg, NameOut, DateOut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnClick = (Button) findViewById(R.id.button) ;
btnClick.setOnClickListener(this);
Name = (EditText) findViewById(R.id.textenter) ;
Date = (EditText) findViewById(R.id.editText) ;
msg = (TextView) findViewById(R.id.txtviewOut) ;
NameOut = (TextView) findViewById(R.id.txtoutName) ;
DateOut = (TextView) findViewById(R.id.txtOutDate) ;
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void onClick(View v)
{
if (v == btnClick)
{
if (Name.equals("") == false && Date.equals("") == false)
{
NameOut = Name;
DateOut = Date;
msg.setVisibility(View.VISIBLE);
}
else
{
msg.setText("Please complete both fields");
msg.setVisibility(View.VISIBLE);
}
}
return;
}
Your
Activity
must implementView.OnClickListener
, like this:And inside
MainActivity
override the methodonClick()
, like this:When you define an
OnClickListener
(or any listener) this wayyou need to
implement
theOnClickListener
in yourActivity
.in Activity java class you would need a method first to find the view of the button as :
after this set on click listener
and override onClick method for your functionality .I have found a fully working example here : http://javainhouse.blogspot.in/2016/01/button-example-android-studio.html
This means in other words (due to your current scenario) that your MainActivity need to implement OnClickListener:
This:
means that you want to assign listener for your Button "on this instance"
->
this instance represents OnClickListener and for this reason your class have to implement that interface.It's similar with anonymous listener class (that you can also use):