標題:
Android App - Button
[打印本頁]
作者:
admin
時間:
2012-1-26 23:56
標題:
Android App - Button
程式啟動時的顯示
[attach]998[/attach]
按右邊的圖像按鈕
[attach]999[/attach]
按左上角的按鈕
[attach]1000[/attach]
按左下角按鈕5次
[attach]1001[/attach]
button.java 檔案:
package sample.button;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class ButtonActivity extends Activity {
/** Called when the activity is first created. */
Button Button1, Button2;
ImageButton myImageButton;
Integer counter = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myImageButton = (ImageButton) this.findViewById(R.id.imageButton1);
myImageButton.setOnClickListener(new View.OnClickListener() { // without "View" before
OnClickListener -> error
public void onClick(View v) {
Toast.makeText(ButtonActivity.this, "ImageButton clicked!", Toast.LENGTH_SHORT).show();
}
});
}
public void onButton1Click(View view)
{
Toast.makeText(this, "Button clicked!", Toast.LENGTH_SHORT).show();
Button1 = (Button) this.findViewById(R.id.button1);
Button1.setText(R.string.disable);
}
public void onButton2Click(View view)
{
Button2 = (Button) this.findViewById(R.id.button2);
counter++;
Button2.setText("Times clicked: " + Integer.toString(counter));
}
}
在 /res/drawable 加入 btn_android.png,
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"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:minHeight="52dp"
android:onClick="onButton1Click"
android:text="Click Me"
android:textSize="20dp" />
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="48dp"
android:layout_toRightOf="@+id/button1"
android:src="@drawable/btn_android" />
</RelativeLayout>
<Button
android:id="@+id/button2"
android:layout_width="98dp"
android:layout_height="wrap_content"
android:minHeight="52dp"
android:onClick="onButton2Click"
android:text="@string/enable"
android:textSize="20dp" />
</LinearLayout>
strings.xml 檔案內容
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Click Me</string>
<string name="app_name">Button</string>
<string name="enable">Enable</string>
<string name="disable">Disable</string>
</resources>
歡迎光臨 How2Do (http://forum.how2do.com.hk/)
Powered by Discuz! 7.2