Android Studio Onclick和片段不起作用

时间:2015-05-26 02:03:56

标签: java android android-fragments android-studio onclicklistener

当我点击我的旅行按钮时,它应该用TravelFragment替换Menufragment。但由于某种原因它不起作用,我不知道问题是来自onClicklistener还是我替换片段的方式。当我调试它时,在第32行抱怨,“查看root = inflater.inflate(R.layout.fragment_menu,container,false);”是我的代码。

    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    import android.content.Intent;
    import android.os.Bundle;
    import android.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class MenuFragment extends Fragment {


       public MenuFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_menu, container, false);
    Button TravelButton = (Button) root.findViewById(R.id.travel);

    TravelButton.setOnClickListener(buttonListener);

    return root;
}
private View.OnClickListener buttonListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        switch (v.getId() ){
            case R.id.travel:{
                TravelFragment newFragment = new TravelFragment();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.container, newFragment);
                transaction.addToBackStack(null);
                transaction.commit();
            }
            break;
        }
    }
};

}

这是我的mainactivity的xml代码(FrameLayout在RelativeLayout中,用于包含我可以替换片段的容器,例如:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity">

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></FrameLayout>

    </RelativeLayout>

我无法找到问题所在。请帮忙。我是Android Studio新手,所以请耐心等待我!欢迎大家帮忙。

1 个答案:

答案 0 :(得分:0)

尝试使用此代码:

frag_results frag_results = new frag_results();
                    FragmentManager manager = getActivity().getSupportFragmentManager();
                    manager.beginTransaction().replace(R.id.framelayout_secundary, frag_results, frag_results.getTag()).commit();
相关问题