.NET Developer 在这里刚刚开始使用 Eclipse 和 Android。
谁能以最简单的方式告诉我,用最少的代码行,当一个按钮被点击时如何做某事?
我的按钮有 id button1
,我只想看看在哪里/如何编写 onClick()
处理程序。
假设我将 imageview1
设置为不可见。单击按钮时如何使其可见?
编辑:
谢谢大家,但由于没有一个示例对我有用,我会试试这个:有人可以发布整个代码来完成这项工作吗?不仅仅是方法,因为当我尝试使用您的任何方法时,我都会得到错误,所以很明显还有其他东西丢失了。我需要查看所有内容,从所有导入开始。
最佳答案
/src/com/example/MyClass.java
package com.example
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MyClass extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
ImageView iv = (ImageView) findViewById(R.id.imageview1);
iv.setVisibility(View.VISIBLE);
}
});
}
}
/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Button"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ImageView
android:src="@drawable/image"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/imageview1"
android:visibility="invisible"
/>
</LinearLayout>
关于android - 如何捕捉按钮上的点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5869871/