03.Activity代码
约 316 字大约 1 分钟
生命周期

传参
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class MainTestActivity extends AppCompatActivity {
public static final String testKey = "ssssssss";
private ActivityResultLauncher<Intent> activityResultLauncher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_test);
activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
String returnedResult = result.getData().getStringExtra(testKey);
Toast.makeText(this, "Result: " + returnedResult, Toast.LENGTH_LONG).show();
}
});
View test_01 = findViewById(R.id.test_01);
test_01.setOnClickListener((View v) -> {
Intent intent = new Intent(MainTestActivity.this, Test2Activity.class);
intent.putExtra(testKey, "名称");
Bundle bundle = new Bundle();
bundle.putString("name", "qll");
bundle.putInt("age", 3);
intent.putExtras(bundle);
activityResultLauncher.launch(intent);
});
}
}
Test2Activity
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class Test2Activity extends AppCompatActivity {
private static final String TAG = "Test2Activity ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test2);
Intent intent = getIntent();
Bundle date = intent.getExtras();
Log.i(TAG, "数据:: " + date.getString(MainTestActivity.testKey));
Bundle extras = intent.getExtras();
Log.i(TAG, "数据2:: " + extras.getString("name"));
View test_02 = findViewById(R.id.test_02);
test_02.setOnClickListener((View v) -> {
Intent i = new Intent();
i.putExtra(MainTestActivity.testKey, "cccc");
setResult(RESULT_OK, i);
finish();
});
}
}
事件
点击
Button myButton = findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在这里编写按钮点击后要执行的操作
Toast.makeText(getApplicationContext(), "按钮被点击了", Toast.LENGTH_SHORT).show();
}
});
长按
Button myButton = findViewById(R.id.myButton);
myButton.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// 在这里编写长按按钮后要执行的操作
Toast.makeText(getApplicationContext(), "按钮被长按了", Toast.LENGTH_SHORT).show();
// 返回true表示事件被消耗,不再向下传递;返回false表示事件未被消耗,将继续传递到其他监听器
return true;
}
});