具有多个按钮和不同ID的CustomView Listener(Callback)

时间:2018-10-21 10:22:44

标签: java android

我正在尝试制作一个 SlideButton库,几乎一切都完成了,但是 onClickListener
中存在问题 问题是,当我在XML中使用 customView(即SlideButton) 两次或多次但使用不同的ID ,并且在MainActivity中实现该监听器

所以问题是,即使我在比较具有ID的按钮(如 if(slideButton1.getId()==),当我单击任何按钮时,仅会调用一个 SlideButton(即slideButton1) R.id.btnUp),但没有任何反应。

简而言之,我在具有不同ID的xml中多次使用CustomView,并在MainActivity中使用它,所以总是只调用一个按钮

这是我的CustomView类

public class SlideButton extends LinearLayout implements View.OnClickListener
{
    LinearLayout linearLayout;
    TextView centerText;
    ImageButton slidingButton;

    TypedArray typedArray;
    //shapes
    GradientDrawable buttonCollapse,buttonExpand,backgroundButton;
    String mAttrText;
    Drawable disabledDrawable,enabledDrawable;
    int mAttrId,mAttrButtonPadding,mAttrTextPadding,
            mAttrTextSize,mAttrTextColor,mAttrRadius,mAttrCollapse,
            mAttrStrokeWidth,mAttrStrokeColor,mAttrExpand,mAttrBackColor,
            mAttrBackStrokeColor,mAttrBackStrokeWidth;

    //it is the variable that says that the button is expand or not.
    private boolean active;
    //it is the initial width of the button. we need to save it so we can back to the initial position.
    private int initialButtonWidth;
    SlideListener listener;

    public SlideButton(Context context) {
        super(context);
        init(context,null,-1,-1);
    }

    public SlideButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, -1, -1);
    }

    public SlideButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr, -1);
    }

    @TargetApi(21)
    public SlideButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs, defStyleAttr, defStyleRes);
    }

    public void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {

        attrValue(context,attrs);
        btnCollapse();
        btnExpand();
        backButton();
        dynamicLayout(context);
        dynamicButton(context);
        dynamicTextView(context);
        new ShineEffect(centerText);

        try {
            listener = (SlideListener) context;
        }catch (ClassCastException e){
            e.printStackTrace();
        }
    }

    /*
  -----------------------------------------getting attr values---------------------------------------------------------
     */
    private void attrValue(Context context,AttributeSet attrs){

        typedArray=context.getTheme().obtainStyledAttributes(attrs,R.styleable.SlideButton,0,0);
        try {

            //attribute for text
            mAttrText = typedArray.getString(R.styleable.SlideButton_text);
            mAttrTextPadding=typedArray.getDimensionPixelSize(R.styleable.SlideButton_textPadding,0);
            mAttrTextSize=typedArray.getDimensionPixelSize(R.styleable.SlideButton_textSize,0);
            mAttrTextColor=typedArray.getColor(R.styleable.SlideButton_textColor, Color.GRAY);

            //attribute for  button
            mAttrButtonPadding =typedArray.getDimensionPixelSize(R.styleable.SlideButton_buttonPadding,0);
            mAttrRadius=typedArray.getDimensionPixelSize(R.styleable.SlideButton_cornerRadius,45);
            mAttrCollapse=typedArray.getColor(R.styleable.SlideButton_collapseColor,Color.WHITE);
            mAttrExpand=typedArray.getColor(R.styleable.SlideButton_expandColor,Color.WHITE);
            disabledDrawable=typedArray.getDrawable(R.styleable.SlideButton_collapseIcon);
            enabledDrawable=typedArray.getDrawable(R.styleable.SlideButton_expandIcon);
            mAttrStrokeColor=typedArray.getColor(R.styleable.SlideButton_strokeColor,Color.parseColor("#ee071a32"));
            mAttrStrokeWidth=typedArray.getDimensionPixelSize(R.styleable.SlideButton_strokeWidth,3);

            //attribute for background
            mAttrBackColor=typedArray.getColor(R.styleable.SlideButton_backColor,Color.parseColor("#ee071a32"));
            mAttrBackStrokeColor=typedArray.getColor(R.styleable.SlideButton_backStrokeColor,Color.WHITE);
            mAttrBackStrokeWidth=typedArray.getDimensionPixelSize(R.styleable.SlideButton_backStrokeWidth,3);
        }
        finally {
            typedArray.recycle();
        }
    }

    /*
  -----------------------------------------btn collapse shape---------------------------------------------------------
     */

    private void btnCollapse(){
        buttonCollapse = new GradientDrawable();
        buttonCollapse.setShape(GradientDrawable.RECTANGLE);
        buttonCollapse.setCornerRadius(mAttrRadius);
        buttonCollapse.setColor(mAttrCollapse);
        buttonCollapse.setStroke(mAttrStrokeWidth,mAttrStrokeColor);
    }

     /*
  -----------------------------------------btn expand shape---------------------------------------------------------
     */

    private void btnExpand(){
        buttonExpand = new GradientDrawable();
        buttonExpand.setShape(GradientDrawable.RECTANGLE);
        buttonExpand.setCornerRadius(mAttrRadius);
        buttonExpand.setColor(mAttrExpand);
        buttonExpand.setStroke(mAttrStrokeWidth,mAttrStrokeColor);
    }

     /*
  -----------------------------------------btn background shape---------------------------------------------------------
     */

    private void backButton(){
        backgroundButton = new GradientDrawable();
        backgroundButton.setShape(GradientDrawable.RECTANGLE);
        backgroundButton.setCornerRadius(mAttrRadius);
        backgroundButton.setColor(mAttrBackColor);
        backgroundButton.setStroke(mAttrBackStrokeWidth,mAttrBackStrokeColor);
    }

     /*
  -----------------------------------------dynamic linear layout---------------------------------------------------------
     */

    private void dynamicLayout(Context context) {
        linearLayout=new LinearLayout(context);
        //LayoutParams are used by views to tell their parents how big the view wants to be for both in width and height
        linearLayout.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.setBackground(backgroundButton);
        linearLayout.setGravity(Gravity.START);
        //add the view to parent layout
        addView(linearLayout);
    }

     /*
  -----------------------------------------dynamic text view---------------------------------------------------------
     */

    private void dynamicTextView(Context context) {
        centerText=new TextView(context);
        centerText.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
        centerText.setGravity(Gravity.CENTER);
        centerText.setText(mAttrText);
        centerText.setPadding(mAttrTextPadding,0,0,0);
        centerText.setTextSize(mAttrTextSize);
        centerText.setTextColor(mAttrTextColor);
        linearLayout.addView(centerText);
    }

     /*
  -----------------------------------------dynamic image button--------------------------------------------------------
     */

    private void dynamicButton(Context context) {
       slidingButton=new ImageButton(context);
       LayoutParams params=new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
       params.setMargins(3,3,3,3);
       slidingButton.setLayoutParams(params);
       slidingButton.setId(mAttrId);
       slidingButton.setImageDrawable(disabledDrawable);
       slidingButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
       slidingButton.setPadding(mAttrButtonPadding,mAttrButtonPadding,mAttrButtonPadding,mAttrButtonPadding);
       slidingButton.setBackground(buttonCollapse);
       linearLayout.addView(slidingButton);
       slidingButton.setOnClickListener(this);
    }

     /*
  -----------------------------------------listener---------------------------------------------------------
     */

    @Override
    public void onClick(View view) {

        if(active){
            collapseButton();
        }
        else {
            initialButtonWidth=slidingButton.getWidth();
            expandButton();
        }
    }

    public interface SlideListener{
        void onClick(boolean active);
    }

    public void setOnSlideListener(SlideListener listener){
        this.listener=listener;
    }

     /*
  -----------------------------------------expand animation---------------------------------------------------------
     */

    private void expandButton()
    {
        final ValueAnimator widthAnimator = ValueAnimator.ofInt(slidingButton.getWidth(),getWidth()-6);
        widthAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation)
            {
                ViewGroup.LayoutParams params = slidingButton.getLayoutParams();
                params.width = (Integer) widthAnimator.getAnimatedValue();
                slidingButton.setLayoutParams(params);
                slidingButton.setEnabled(false);
            }
        });

        widthAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                active = true;

                if (listener!=null) {
                    listener.onClick(true);
                }
                slidingButton.setEnabled(true);
                slidingButton.setImageDrawable(enabledDrawable);
                slidingButton.setBackground(buttonExpand);
            }
        });
        widthAnimator.start();
    }

     /*
  -----------------------------------------collapse animation---------------------------------------------------------
     */

    private void collapseButton() {

        final ValueAnimator widthAnimator = ValueAnimator.ofInt(slidingButton.getWidth(), initialButtonWidth);
        widthAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation)
            {
                ViewGroup.LayoutParams params =  slidingButton.getLayoutParams();
                params.width = (Integer) widthAnimator.getAnimatedValue();
                slidingButton.setLayoutParams(params);
                slidingButton.setEnabled(false);
            }
        });

        widthAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                active = false;

                if(listener!=null){
                    listener.onClick(false);
                }
                slidingButton.setEnabled(true);
                if(disabledDrawable!=null){
                    slidingButton.setImageDrawable(disabledDrawable);
                }
                slidingButton.setBackground(buttonCollapse);
            }
        });
        widthAnimator.start();
    }
}

这是使用自定义视图的xml

<com.greenlab.hackme.slidebutton.SlideButton
        android:id="@+id/btnUp"

        android:layout_width="260dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        custom:buttonPadding="20dp"
        custom:cornerRadius="45dp"
        custom:collapseColor="@android:color/white"
        custom:expandColor="@android:color/white"
        custom:collapseIcon="@drawable/collapsed"
        custom:expandIcon="@drawable/expanded"
        custom:strokeColor="#ee071a32"
        custom:strokeWidth="3dp"
        custom:backStrokeColor="@android:color/white"
        custom:backColor="#ee071a32"
        custom:backStrokeWidth="2dp"
        custom:text="Tap to Activate"
        custom:textPadding="20dp"
        custom:textSize="8dp"
        custom:textColor="#a39c9c">
    </com.greenlab.hackme.slidebutton.SlideButton>

    <com.greenlab.hackme.slidebutton.SlideButton
        android:id="@+id/btnDown"

        android:layout_width="260dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="100dp"
        custom:buttonPadding="15dp"
        custom:cornerRadius="25dp"
        custom:collapseColor="@android:color/white"
        custom:expandColor="@android:color/white"
        custom:collapseIcon="@drawable/collapsed"
        custom:expandIcon="@drawable/expanded"
        custom:strokeColor="#ee071a32"
        custom:strokeWidth="3dp"

        custom:backStrokeColor="@android:color/white"
        custom:backColor="#ee071a32"
        custom:backStrokeWidth="2dp"

        custom:text="Tap to Activate"
        custom:textPadding="20dp"
        custom:textSize="8dp"
        custom:textColor="#b3a9a9">
    </com.greenlab.hackme.slidebutton.SlideButton>

这是MainActivity实施监听器

public class MainActivity extends AppCompatActivity implements SlideButton.SlideListener {

    SlideButton slideButton1,slideButton2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        slideButton1=findViewById(R.id.btnUp);
        slideButton2=findViewById(R.id.btnDown);

        slideButton1.setOnSlideListener(this);
        slideButton2.setOnSlideListener(this);
    }


    @Override
    public void onClick(boolean active) {

        if(slideButton1.getId()==R.id.btnUp) {

            if(active){
                Toast.makeText(this, "Active Up", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(this, "Deactivate Up", Toast.LENGTH_SHORT).show();
            }

        }else if(slideButton2.getId()==R.id.btnDown){

            if(active){
                Toast.makeText(this, "Active Down", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(this, "Deactivate Down", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

这是attribute.xml文件

<resources>
    <declare-styleable name="SlideButton">

        <attr name="text" format="string"/>
        <attr name="textPadding" format="dimension"/>
        <attr name="textSize" format="dimension"/>
        <attr name="textColor" format="color"/>

        <attr name="buttonPadding" format="dimension"/>
        <attr name="cornerRadius" format="dimension"/>
        <attr name="collapseColor" format="color"/>
        <attr name="expandColor" format="color"/>
        <attr name="collapseIcon" format="reference"/>
        <attr name="expandIcon" format="reference"/>
        <attr name="strokeWidth" format="dimension"/>
        <attr name="strokeColor" format="color"/>

        <attr name="backStrokeWidth" format="dimension"/>
        <attr name="backStrokeColor" format="color"/>
        <attr name="backColor" format="color"/>
    </declare-styleable>
</resources>

1 个答案:

答案 0 :(得分:0)

尝试像这样定义回调interface

public interface SlideListener {
    void onClick(SlideButton button, boolean active);
}

SlideButton类中的任何地方,调用onClick并传递当前引用:

if (listener != null) {
    listener.onClick(SlideButton.this, true/false);
}

然后在MainActivity中按以下方式检查单击的按钮的ID:

@Override
public void onClick(SlideButton button, boolean active) {

    if(button.getId() == R.id.btnUp) {
        if(active){
            Toast.makeText(this, "Active Up", Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(this, "Deactivate Up", Toast.LENGTH_SHORT).show();
        }
    } else if(button.getId() == R.id.btnDown) {
        if(active){
            Toast.makeText(this, "Active Down", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Deactivate Down", Toast.LENGTH_SHORT).show();
        }
    }
}