以编程方式为场景中的按钮设置onClickListeners

时间:2015-03-08 00:08:45

标签: java android android-4.4-kitkat scene

我有两个包含相同按钮的布局

layout_1.xml

  <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    <Button
        android:id="@+id/button_1"
        android:text="button2"
        android:background="@android:color/black"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    </RelativeLayout>

layout_2.xml

<RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    <Button
        android:id="@+id/button_1"
        android:text="button2"
        android:background="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    </RelativeLayout>

请假设这些都是有效的布局等。(我只是添加相关代码。)。

因此,在我的片段中,我在layout_1.xml中充气并使用onCreateView。我想使用button_1在两个场景之间切换。 我可以在button_1期间在layout_1.xml中为onCreateView()设置听众。 问题是尝试在第二个视图中设置该按钮的监听器.i.e。监听器没有激活第二个场景(layout_2.xml)。因此我可以在两个场景之间切换。有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:6)

实际上,这样做的正确方法是在第二个场景中定义要执行的操作:

mSecondScene.setEnterAction(new Runnable() {
        @Override
        public void run() {
                 ((Button) mSecondScene.getSceneRoot().findViewById(R.id. button_1)).setOnClickListener( ... );
    }

这将允许您在View上设置ClickListener,而不将数据绑定到通用单击侦听器方法。然后你可以执行转换到第二个场景和中提琴。

答案 1 :(得分:2)

一般情况下,使用相同id的多个视图并不是一个好主意。这就是造成混乱的原因。

注意:以下是OP使用的适合其特定需求的解决方案:

一个简单的解决方案是在XML文件中使用onClick属性。您可以将相同的onClick方法分配给多个项目。像这样:

         

         

在你的activity.java中添加:

public void buttonClicked(View v){

    Log.d("TAG","Button clicked!!"
    // do stuff here

}

第二个选项

当您使用id button_1为一个按钮设置监听器时,它不会为两个按钮设置listener,而只会为第一个设置它。如果您想为两者设置相同的listener,您只需将这些按钮指定为ids,然后为它们指定相同的listener

这是你应该做的:

Listener myListener = new Listener(){.. blah blah....};

((Button) findViewById(R.id.some_id)).setListerner(myListener);
((Button) findViewById(R.id.some_other_id)).setListerner(myListener);

第3个选项

findViewById(R.id.id_of_layout1).findViewById(R.id.button_1)
findViewById(R.id.id_of_layout2).findViewById(R.id.button_1)

在这种情况下,您需要为布局文件添加一些id,例如:layout_1.xml:

<RelativeLayout
        android:id="+id/id_of_layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    <Button
        android:id="@+id/button_1"
        android:text="button2"
        android:background="@android:color/black"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    </RelativeLayout>
相关问题