【发布时间】:2015-09-03 17:54:32
【问题描述】:
我有一个包含 layout_a 的片段。在该片段下,我动态添加了一个 textview 和一个按钮,它是 layout_b 的一部分。我无法让按钮(layout_b 的 myButton 部分)侦听器工作。我还有其他按钮,它们是 layout_a 的一部分并且正在工作。要在 layout_b 中使用按钮侦听器,我正在执行以下步骤。
public View onCreateView(LayoutInflater in, ViewGroup vgroup, Bundle savedInstanceState) {
testView = inflater.inflate(R.layout.layout_b, container, false);
...
myButton = (Button) testView.findViewById(R.id.my_button);
...
}
private void configureSuggestedEmailButton() {
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("test", "click");
...
}
});
}
片段布局是layout_a,按钮在layout_b,我需要做些不同的事情吗?
更新代码:
public View onCreateView(LayoutInflater in, ViewGroup vgroup, Bundle savedInstanceState) {
//this view is used to setup buttons from layout_a, current activity has this layout
view = inflater.inflate(R.layout.layout_a, container, false);
//this view is used to manage to the layout_b
testView = inflater.inflate(R.layout.layout_b, container, false);
myButton = (Button) testView.findViewById(R.id.my_button);
configureSuggestedEmailButton();
}
private void configureSuggestedEmailButton() {
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("test", "click");
}
});
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/layout_b"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
style="?android:attr/buttonStyleSmall"
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="30dip"
android:text="Yes"
android:textSize="10sp"
/>
</RelativeLayout>
</LinearLayout>
【问题讨论】:
-
所以您正在将这个新部分添加到 layout_a 中,对吧?在你的代码中你是在哪里做的?
-
@Diyoda 我有一个函数调用,它执行以下
LinearLayout row = (LinearLayout) getActivity().getLayoutInflater().inflate(R.layout.layout_b, null); LinearLayout eLayout = (LinearLayout) editTextField.getParent(); eLayout.addView(errorRow, someIndex); ...按钮显示在屏幕上,但监听器没有响应。我的看法是按钮侦听器未附加到片段 -
你能用所有相关代码更新问题吗,我一定会帮你的
-
@diyoda 我更新了代码,如果您需要更多信息,请告诉我。
-
看看我的代码。可能存在语法问题,我没有使用我的 IDE 来写这个。我想传达这个想法。这是你已经这样做的方式吗?我希望你错过了你认为不相关的代码部分。
标签: android button android-fragments layout