在片段的方法中调用一个按钮

时间:2014-08-14 02:06:46

标签: android android-fragments android-button

您能帮助将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>

2 个答案:

答案 0 :(得分:0)

将param添加到按钮xml

android:onClick="callPc"

或者你可以初始化你的按钮对象全局(在初始化类之后) 然后你可以随时随地拨打你的按钮

或者您可以像这样设置param到callPc()

public void callPc(Button btn)
{
    btn.setOnClickListener(...);
}

答案 1 :(得分:0)

你必须在onViewCreated方法中为onClicklistener编写代码,因为你正在使用片段......

 @Override  
public void onViewCreated(View view, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);



    pc.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {   
          // your action for button click 


         }
         }); 
         }