没有从动态创建的子视图中单击事件

时间:2013-10-21 12:27:59

标签: android view

来自ViewGroup类中的动态创建的Button(名为“Controller”)我尝试捕获click-Event以将其重定向到Activity-Context中的Handler。不幸的是,事件没有被激发,或者有些人阻止它。

请仔细查看我的示例代码(注意:它只是从头脑中写出来的。不知道语法是否正确),看看我的意思......

活动:

public class Main extends Activity {
private Controller mController;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    mController = new Controller(this, mHandler);
    mController.initControllerViews();
}

private Handler mHandler = new Handler() {
    public void handleMessage(Message msg)
    {
        // ... here I expect the message from clicked view
                    if (msg.obj) {
                        Log.v("XXX", "obj="+msg.obj.toString());
                    }
        super.handleMessage(msg);
    }
};
}

控制器

public class Controller {
private Context mContext;
private Handler mHandler;

public Controller(Context context, Handler handler)
{
    mContext = context;
    mHandler = handler;
}

public void initControllerViews()
{
    Activity activity = (Activity)mContext;

    LayoutInflater inflater = (LayoutInflater)activity.getSystemService(LAYOUT_INFLATER);
    LinearLayout layout = (LinearLayout)activity.findViewById(R.layout.layout1);
    Button btn = (Button)inflater.inflate(R.layout.Button, null);
    btn.setOnClickListener(new OnClickListener() {
        public void onClick(View v)
        {
                            Log.v("XXX", "v="+v.toString());
            Message msg = Message.obtain(mHandler);
            msg.obj = v;
            mHandler.sendMessage(msg);
        }
    });
    layout.addView(btn);
}
}

如您所见, Controller 计划为预定义布局内可点击项目的构建类,并作为其事件的调度程序。

问题是,虽然为它安装了onclick-listener,但从未生成click事件。

有没有人有想法,这里出了什么问题,或者我忘了实施什么?

非常感谢+最诚挚的问候!

1 个答案:

答案 0 :(得分:0)

确定。终于在家了,我发现了我的错误:

LinearLayout layout = (LinearLayout)activity.findViewById(R.layout.layout1);
Button btn = (Button)inflater.inflate(R.layout.Button, null);

因此我做得相当愚蠢。这是纠正:

LinearLayout layout = (LinearLayout)activity.findViewById(R.layout.layout1);
View itemView = inflater.inflate(R.layout.Button, null);
Button btn = (Button)itemView.findViewById(R.id.btn1);
// ...

希望能帮助别人......