其他直接上代码
- <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 imagePic 按钮前面的图片 为空则为默认
- * @param text 按钮的文本 为空则为默认
- */
-
- public MyViewTest(Context context, Integer backgroudPic , Integer imagePic , String text) {
- super(context);
- // TODO Auto-generated constructor stub
- if(backgroudPic==null)
- this.setBackgroundResource(R.drawable.my_music_button);
- else
- this.setBackgroundResource(backgroudPic);
-
- ImageView imageView = new ImageView(context);
- if(imagePic==null)
- imageView.setImageResource(R.drawable.style1_button_icon_normal);
- else
- imageView.setImageResource(imagePic);
- imageView.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(imageView);
- this.addView(textView , lp1);
-
- }
-
- }
其中R.drawable.my_music_button 是一个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>
本文转自 最牛傻蛋 51CTO博客,原文链接:http://blog.51cto.com/zuiniuwang/718260,如需转载请自行联系原作者