Android View点击事件写法

2017/8/16 10:52:11 人评论 次浏览 分类:开源项目

第一种写法:
public class MainActivity extends AppCompatActivity implements  OnClickListener {

    private Button one_bt;
    private Button two_bt;
    private Button three_bt;
    private Button four_bt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.one_bt).setOnClickListener(this);
        findViewById(R.id.two_bt).setOnClickListener(this);
        findViewById(R.id.three_bt).setOnClickListener(this);
        findViewById(R.id.four_bt).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.one_bt:
                Toast.makeText(this,"这就是第一种写法",Toast.LENGTH_SHORT).show();
                break;

            case R.id.two_bt:

                startActivity(new Intent(this,TwoActivity.class));
                break;



            case R.id.three_bt:
                startActivity(new Intent(this,ThreeActivity.class));
                break;



            case R.id.four_bt:
                startActivity(new Intent(this,FourActivity.class));
                break;


        }

    }

第二种写法


 
public class TwoActivity extends AppCompatActivity { @Override  protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
    } public void onTest(View v){
        Toast.makeText(this,"这就是第二种写法",Toast.LENGTH_SHORT).show();

    }
}

第三种写法


public class ThreeActivity extends AppCompatActivity { @Override  protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_three);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override  public void onClick(View view) {
                Toast.makeText(ThreeActivity.this,"这就是第三种写法",Toast.LENGTH_SHORT).show();
            }
        });
    }
}


附件下载

相关资源

共有访客发表了评论 网友评论

验证码: 看不清楚?