我刚尝试在Android Studio中为Button添加一个OnClickListener(),但我收到上述错误,建议我更改为-source 8或更高版本。
下面的代码块有什么问题?
public class MainActivity extends AppCompatActivity
{
public Button butTest;
//---- THIS BLOCK HERE CAUSES PROBLEM ---->
public final View.OnClickListener butTest_OnClickListener = new View.OnClickListener()
{
@Override
public void onClick( View view )
{
//Toast.makeText( this, "Button1 clicked.", Toast.LENGTH_SHORT ).show();
}
}
// <<------ END OF PROBLEM
@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
butTest = (Button) findViewById( R.id.butTest );
butTest.setOnClickListener( butTest_OnClickListener );
}
}
答案 0 :(得分:1)
您需要将其放在方法中(例如onCreate)。您可以执行以下操作:
@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
butTest = (Button) findViewById( R.id.butTest );
butTest.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick( View view )
{
//Toast.makeText( this, "Button1 clicked.", Toast.LENGTH_SHORT ).show();
}
});
}
希望它有所帮助。