【发布时间】:2014-08-14 02:06:46
【问题描述】:
你能帮忙引用一个从 OnCreateView 到它的方法的按钮吗?
这是我的代码。
public class static placeholder extends Fragment {
public placeholder()
{ ... }
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
Button pc = (Button) rootView.findViewById(R.id.btnPc);
...
}
//Call the button pc to this method
public void callPc()
{
//Reference the button Here!
}
}
我已经尝试使用getView().findViewById(R.id.btnPc) 调用它,但它不起作用。我也使用了getActivity(),但它也不起作用。
fragment_main.xml
<RelativeLayout
android:id="@+id/weightLimitResultBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/btnPc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Button" />
</RelativeLayout>
【问题讨论】:
-
onCreateView的返回值在哪里? -
return rootviewinonCreateView -
你的意思是你想要一个 onClickListener 附加到片段中的按钮上?
-
覆盖
onActivityCreated()和setOnClickListener()内部? -
我已经尝试使用 getView().findViewById(R.id.btnPc) 调用它,但它不起作用。我也使用了 getActivity(),但它也不起作用。你能告诉我它是如何如何不起作用的吗?它会抛出错误吗?崩溃了?
标签: android android-fragments android-button