In this Android development tutorial, Mark will show you how to create a custom button and place it within your Android application. If you’ve been working with Android development, you might be surprised how easy it easy to produce and use a custom button. The custom button graphic can have three states, and Mark will you show you the XML to display the button and Java code to make the button execute a task.
main.xml
1 2 3 4 5 6 7 8 | <?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" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/custom_button" android:id="@+id/btnTv"></Button> </LinearLayout> |
custom_button.xml
1 2 3 4 5 6 7 | <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/btn_over" android:state_pressed="true" /> <item android:drawable="@drawable/btn_normal" /> </selector> |
CustomButtonExampleActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package tv.learntoprogram.customButton; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class CustomButtonExampleActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btn = (Button)findViewById(R.id.btnTv); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "You pressed the custom button",Toast.LENGTH_SHORT).show(); } }); } } |


