java - 如何在 Activity 类中实现方法
问题描述
我刚刚开始使用 Android Studio 学习 Android 编程,不幸的是,我遇到了一个可能非常简单的问题,即在主活动的布局文件中,我将 startActivity() 方法分配给android:onClick
了两个按钮(android:onClick="startActivity()")。
现在我应该在 MainActivity 类中实现 startActivity() 方法,但是....我不知道该怎么做。
我看到我应该在 MainActivity: public void startActivity(View v)
。我尝试了几个小时,一直在寻找解决方案,但我已经失去了希望。
特别是我可以实现例如 View.OnClickListener 但方法 startActivity() 不能再做。我怎么能实现这个方法?
我将 startActivity() 方法分配给 activity_main.xml 中两个按钮的 android:onClick 属性:
<Button
android:id="@+id/button"
android:onClick="startActivity()"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="24dp"
android:text="@string/button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="OnClick" />
<Button
android:id="@+id/button2"
android:onClick="startActivity()"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="16dp"
android:text="@string/button2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
tools:ignore="OnClick" />
接下来我应该在 MainActivity 类中,实现 startActivity() 方法但是....我不知道该怎么做:
public class MainActivity extends AppCompatActivity implements startActivity() {
Button b1, b2;
EditText et1, et2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.button);
b2 = findViewById(R.id.button2);
et1 = findViewById(R.id.editText);
et2 = findViewById(R.id.editText2);
public void startActivity(View v) {
if (v.getId() == R.id.button) {
String name = et1.getText().toString();
int age = Integer.parseInt(et2.getText().toString());
Intent i = new Intent(this, ResultActivity.class);
i.putExtra("name", name);
i.putExtra("age", age);
startActivity(i);
} else {
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.google.pl/"));
startActivity(i); }
}
}
解决方案
您错误地使用了onClick
属性。这是错误的:
android:onClick="startActivity()"
它应该是:
android:onClick="startActivity"
阅读更多https://developer.android.com/guide/topics/ui/controls/button#HandlingEvents
建议
您应该避免android:onClick
在您的 xml 中使用。改为使用onClickListener
。将你的逻辑和 UI 布局分开很重要,这样每当你的 xml 布局发生变化时,你就不需要考虑太多。使用这样的东西:
Button button = (Button) findViewById(R.id.your_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something here when button is clicked.
}
});
推荐阅读
- excel - Excel vba交错单元格值
- php - 查找 wordpress 功能位置
- android - Android Studio 不显示 recyclerview 的任何属性
- plot - NetCDF 文件的数据提取和转换
- python - 有没有办法使用 zipline 在本地创建管道?
- jquery - 动态更改弹出框中的图像内容
- bash - 使用 Git 检测未跟踪的文件以触发 Shell 脚本中的退出代码 0
- java - @OneToOne 映射在我的 Java Spring 项目中不起作用
- http - 为什么有些 API 文档会指定表单数据值类型或内容头值类型?
- python-3.x - PyQT5 - 如何让 QApplication 在加载后调用方法?