自定義了一個Button按鈕,效果如圖,有自定義背景(可根據文字長短擴充),自定義按鈕圖檔和文字背景圖檔擴充,參考http://www.7747.net/kf/201104/88131.html 這個文章,http://blog.csdn.net/greatstar/archive/2010/10/12/5936177.aspx 和這個文章。使用draw9patch時遇到不能啟動,原因是Android 2.3少了一個包,swing-worker-1.2 下載下傳放在android-sdk\tools\lib 下遍可以正常使用。
其他直接上代碼
?[Copy to clipboard]Download zuiniuwang.java
- <span style="font-size: 14px">import android.content.Context;
- import android.view.ViewGroup;
- import android.widget.ImageView;
- import android.widget.LinearLayout;
- import android.widget.RelativeLayout;
- import android.widget.TextView;
- public class MyViewTest extends RelativeLayout {
- private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
- private final int FP = LinearLayout.LayoutParams.FILL_PARENT;
- private final static String TAG = MyViewTest.class.getSimpleName();
- /**
- *
- * @param context
- * @param backgroudPic 背景圖檔的ID 為空則為預設
- * @param p_w_picpathPic 按鈕前面的圖檔 為空則為預設
- * @param text 按鈕的文本 為空則為預設
- */
- public MyViewTest(Context context, Integer backgroudPic , Integer p_w_picpathPic , String text) {
- super(context);
- // TODO Auto-generated constructor stub
- if(backgroudPic==null)
- this.setBackgroundResource(R.drawable.my_music_button);
- else
- this.setBackgroundResource(backgroudPic);
- ImageView p_w_picpathView = new ImageView(context);
- if(p_w_picpathPic==null)
- p_w_picpathView.setImageResource(R.drawable.style1_button_icon_normal);
- else
- p_w_picpathView.setImageResource(p_w_picpathPic);
- p_w_picpathView.setId(1);
- RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
- ViewGroup.LayoutParams.WRAP_CONTENT);
- lp1.addRule(RelativeLayout.RIGHT_OF , 1);
- TextView textView = new TextView(context);
- if(text==null)
- textView.setText("my custom button");
- else
- textView.setText(text);
- this.addView(p_w_picpathView);
- this.addView(textView , lp1);
- }
- }
?[Copy to clipboard]Download zuiniuwang.xml
- <span style="font-size: 14px"><?xml version="1.0" encoding="UTF-8"?>
- </span>
- <selector xmlns:android="http://schemas.android.com/apk/res/android"><span style="font-size: 14px">
- </span><item android:drawable="@drawable/my_button_bg" android:state_pressed="true"><span style="font-size: 14px">
- </span><item android:drawable="@drawable/my_button_bg" android:state_focused="true"><span style="font-size: 14px">
- </span><item android:drawable="@drawable/my_music_button_bg"><span style="font-size: 14px">
- </span></item></item></item></selector><span style="font-size: 14px">
- </span>