以编程方式创建布局并设置ClickListener(android)

时间:2015-07-22 10:46:36

标签: java android android-layout listener

我需要创建一个算法。我有方法它的创建布局,在这个布局中我需要在这个布局中指定clickListener。我什么都想不到,请帮我这么做。

此方法创建布局

public LinearLayout createLinearLayout(int i) {
    LinearLayout linLayout = new LinearLayout(context);
    linLayout.setOrientation(LinearLayout.HORIZONTAL);
    LinearLayout.LayoutParams paramsLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    paramsLayout.setMargins(0, 0, 0, 10);
    linLayout.setLayoutParams(paramsLayout);
    linLayout.setBackgroundColor(Color.parseColor("#26000000"));

    linLayout.setId(i);

    return linLayout;
}

我不知道听众在布局中是如何做的,我这样做,但它不起作用

View.OnClickListener myOnlyhandler = new View.OnClickListener() {
    public void onClick(View v) {
        switch(v.getId()) {
            case 0:
                Log.e("0", "0");
                break;
            case 1:
                Log.e("1", "1");
                break;
        }
    }
};

2 个答案:

答案 0 :(得分:1)

添加: linLayout.setOnClickListener(myOnlyHandler)

我认为您还必须设置linLayout.setClickable(true)

希望它有所帮助;)

答案 1 :(得分:0)

我认为您忘记将点击监听器设置为布局linLayout.setOnClickListener(myOnlyhandler);

public LinearLayout createLinearLayout(int i) {
        LinearLayout linLayout = new LinearLayout(context);
        linLayout.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout.LayoutParams paramsLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        paramsLayout.setMargins(0, 0, 0, 10);
        linLayout.setLayoutParams(paramsLayout);
        linLayout.setBackgroundColor(Color.parseColor("#26000000"));

        linLayout.setOnClickListener(myOnlyhandler);

        linLayout.setId(i);
        return linLayout;
    }