java android 2.2.4
package com.example.xinwei.test;import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
Button button1=(Button)findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "you clicked button1", Toast.LENGTH_SHORT).show();
}
});
}
}
效果图:
这个代码比较简单,就是添加一个事件,然后弹出一条信息。我还有另外一种比较简单的方法也可以,首先在frist_layout.xml文件里添加个按钮:
<Button
android:id="@+id/button_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button_2"
android:onClick="myClick"
></Button>
然后把主文件修改成这样:
package com.example.xinwei.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
Button button1=(Button)findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "you clicked button1", Toast.LENGTH_SHORT).show();
}
});
}
void myClick(View v){
Toast.makeText(this, "这是我的方法", Toast.LENGTH_SHORT).show();
}
效果图:
页:
[1]