「Android開発」Buttonイベントを実現する方法のまとめ
1.処理方法1:
ButtonDemo_Startnews24ctivity.java
package com.android.ButtonSample_Startnews24.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ButtonDemo_Startnews24ctivity extends Activity {
Button myButton1,myButton2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton1=(Button)findViewById(R.id.myButton1);
myButton2=(Button)findViewById(R.id.myButton2);
//匿名クラスでButtonイベントを登録
myButton1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(ButtonDemo_Startnews24ctivity.this, “テストボタン1をクリック",Toast.LENGTH_LONG).show();
}
});
myButton2.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(ButtonDemo_Startnews24ctivity.this, “テストボタン2をクリック",Toast.LENGTH_LONG).show();
}
});
}
}
2.処理方法2:
ButtonDemo_Startnews24ctivity.java
package com.android.ButtonSample_Startnews24.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ButtonDemo_Startnews24ctivity extends Activity {
Button myButton1,myButton2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton1=(Button)findViewById(R.id.myButton1);
myButton2=(Button)findViewById(R.id.myButton2);
myButton1.setOnClickListener(new ButtonClick());
myButton2.setOnClickListener(new ButtonClick());
}
//OnClickListener応答クラス
class ButtonClick implements OnClickListener
{
public void onClick(View v)
{
switch (v.getId()) {
case R.id.myButton1:
Toast.makeText(ButtonDemo_Startnews24ctivity.this, “button1のクリック",Toast.LENGTH_LONG).show();
break;
case R.id.myButton2:
Toast.makeText(ButtonDemo_Startnews24ctivity.this, “button2のクリック",Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
}
3.main.xml
<?xml version="1.0″ encoding="utf-8″?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/myButton1″
android:text="button1 "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/myButton2″
android:text="button2 "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
4.strings.xml
<?xml version="1.0″ encoding="utf-8″?>
<resources>
<string name="hello">arkgame.com, code change world</string>
<string name="app_name">ButtonSample_Startnews24</string>
</resources>