0

from an dynamically created Button inside a ViewGroup-class (named 'Controller') I try to catch an click-Event to redirect it to a Handler in Activity-Context. Unfortunately the event isn't fired up OR somewhat else blocks it.

Please take a closer look to my example code (note: it's just written from mind. don't know if syntax is correct), to see what I mean...

the Activity:

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);
    }
};
}

the Controller

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);
}
}

As you can see the Controller is planned as a buildup-Class for clickable items inside a pre-defined layout and as a dispatcher of their events.

The problem is, that the click-event is never generated, although a onclick-listener is installed for it.

Has anyone an idea, what's going wrong here or what I could have forgotten to implement?

Thanks a lot + best regards!

4

1 回答 1

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);
// ...

希望对其他人有所帮助...

于 2013-10-21T17:15:13.310 回答