android 自定义商城app价格正序倒序控件

1.效果图如下:

android 自定义商城app价格正序倒序控件_第1张图片


2.自定义视图布局文件 price_up_down.xml



3.自定义视图代码 PriceUpDownView.java

package net.sytm.priceupdowndemo;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Created by aoc on 2017/4/11.
 */

public class PriceUpDownView extends LinearLayout implements View.OnClickListener {

    private TextView priceView;
    private boolean isUp;
    private Callback callback;

    public PriceUpDownView(Context context) {
        this(context, null);
    }

    public PriceUpDownView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PriceUpDownView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.price_up_down, this);
        priceView = (TextView) findViewById(R.id.price_id);
        priceView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.price_id:
                setDrawable();
                callback.getStatus(isUp);
                break;
        }
    }

    private void setDrawable() {
        Drawable drawable = null;
        if (isUp) {
            isUp = false;
            drawable = getResources().getDrawable(R.drawable.xia);
        }
        else {
            isUp = true;
            drawable = getResources().getDrawable(R.drawable.shang);
        }
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        priceView.setCompoundDrawables(null, null, drawable, null);
        priceView.setCompoundDrawablePadding(8);
        priceView.setTextColor(Color.parseColor("#e02b4d"));
    }

    public  interface Callback {
        void getStatus(boolean isUp);
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }
}


4.使用示例

a.视图布局引用




    


    



b.代码

package net.sytm.priceupdowndemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements PriceUpDownView.Callback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PriceUpDownView upDownView = (PriceUpDownView) findViewById(R.id.price_up_down_id);
        upDownView.setCallback(this);
    }

    @Override
    public void getStatus(boolean isUp) {
        ToastUtil.showShort(this, isUp ? "上" : "下");
    }
}



你可能感兴趣的:(Android)