xml文件配置如下: <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".test"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="test"/> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
java文件配置如下
package com.example.mytest2; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class test extends AppCompatActivity implements View.OnClickListener { private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test); initView(); initlisenter(); } private void initView(){ btn=findViewById(R.id.btn1); } private void initlisenter(){ btn.setOnClickListener(this); } @Override public void onClick(View v) { btn.setText("asad"); } }
主类代码如下
package com.example.mytest2; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test); Intent intent1=new Intent(this,test.class); startActivity(intent1); } }
为什么不在主类中加上最后的intent,单击事件就没有效果呢
你的意思是MainActivity和test两个activity都用了同一个xml布局,test对btn监听了,MainActivity没有监听btn吗?
不同的activity的xml布局,同id的控件也是不同的,需要在对应的activity监听才能生效
第二个Activity初始化后,才会实例化OnClickListener 的接口对象,并在onCreate的方法中将点击事件设置给btn1