Android View的触摸范围很奇怪...帮助我...(自定义视图,inl)

时间:2018-10-23 07:16:15

标签: android view touch margin

我创建了一个自定义视图并添加了setOnClickListener ...

视图的触摸范围很奇怪

我该如何解决?

红色正方形是触摸范围...

enter image description here

enter image description here

XML文件(custom.xml)

<LinearLayout>
    <TextView> ~~
    <TextView> ~~
</LinearLayout>

JAVA代码(custom.java)

public class Custom_Lab_Button extends LinearLayout {
    LinearLayout cus_lab_ll;
    TextView cus_lab_tv1, cus_lab_tv2;

    private void initView(Context context) {
        inflate(getContext(), R.layout.custom_lab_button, this);
//        String infService = Context.LAYOUT_INFLATER_SERVICE;
//        LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(infService);
////        layoutInflater.inflate(R.layout.custom_lab_button, this, false);
//        View v = layoutInflater.inflate(R.layout.custom_lab_button, getContent(), false);
//        addView(v);
        cus_lab_ll = (LinearLayout) findViewById(R.id.cus_lab_ll);
        cus_lab_tv1 = (TextView) findViewById(R.id.cus_lab_tv1);
        cus_lab_tv2 = (TextView) findViewById(R.id.cus_lab_tv2);
    }
    public void setCus_lab_ll_back(int cus_ll_resID) {
        cus_lab_ll.setBackgroundColor(cus_ll_resID);
    }

    public void setCus_lab_ll_margin(LayoutParams layoutParams){
        cus_lab_ll.setLayoutParams(layoutParams);
    }
    public LayoutParams getCus_lab_ll_margin(){
        return (LayoutParams) cus_lab_ll.getLayoutParams();
    }
}

主要Java代码

RelativeLayout cl_img = (RelativeLayout)view.findbyid(R.id.cl_img);
labButton = new Custom_Lab_Button(getActivity());
LinearLayout.LayoutParams tttt = labButton.getCus_lab_ll_margin();
tttt.leftMargin = 300;
tttt.topMargin = 300;
labButton.setCus_lab_ll_back(Color.BLUE);
labButton.setCus_lab_tv1_txt("lab1");
labButton.setCus_lab_ll_margin(tttt);
cl_img.addView(labButton);
labButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(getContext(), "it is lab button 1/", Toast.LENGTH_SHORT).show();
        }
    });

2 个答案:

答案 0 :(得分:0)

我有类似的问题,请使用padding而不是margin

答案 1 :(得分:0)

我解决了..我自己:)

labButton = new Custom_Lab_Button(getContext());
LinearLayout.LayoutParams tttt = labButton.getCus_lab_ll_margin();
tttt.leftMargin = 300;
tttt.topMargin = 300;

labButton.setCus_lab_tv1_txt("lab1");
labButton.setCus_lab_ll_margin(tttt);
labButton.setCus_lab_ll_back(Color.BLUE);
cl_img.setBackgroundColor(Color.GREEN);
cl_img.addView(labButton);
labButton.cus_lab_ll.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(getContext(), "it is lab button 1", Toast.LENGTH_SHORT).show();
        }
    });

[labButton。 cus_lab_ll .setOnClickListener]是原因。