Android SetOnClickListener(this)在Fragment中不起作用

时间:2016-03-31 23:11:26

标签: android android-fragments android-button

我想创建一个App,它有一个NavigationView和一些片段。我没有问题来显示不同的片段并在应用程序内导航。但我没有设法在片段中实现按钮。

点击按钮后没有任何反应。但是我没有任何错误。我在互联网上搜索过,我真的不明白它为什么不起作用。我使用的方法与经典"相同。活动。我想b.setOnClickListener(this)存在问题。我粘贴了我的代码。我希望你们中的一个人能看到我的错误。非常感谢阅读。

Accueil.java(mainActivity):

public class Accueil extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
        HomeFragment.OnFragmentInteractionListener,Settings_accountFragment.OnFragmentInteractionListener {

    NavigationView navigationView;
    private FragmentTransaction fragmentTransaction;
    private FragmentManager fragmentManager;
    private static UserLocalStore userLocalStore;
    private static User user;
    public Intent login;

    //private TextView eventName,eventPlace,eventSchedule;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_accueil);

        userLocalStore=new UserLocalStore(this);
        login=new Intent(this,LoginActivity.class);

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        fragmentManager = getFragmentManager();

        Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(myToolbar);
        getSupportActionBar();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, myToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        loadSelection(0);

    }

    private void loadSelection(int i){
        switch (i){
            case 0:
                HomeFragment homeFragment = new HomeFragment();
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragmentholder,homeFragment);
                fragmentTransaction.commit();
                break;
            case 1:
                Settings_accountFragment settings_account = new Settings_accountFragment();
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragmentholder,settings_account);
                fragmentTransaction.commit();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onStop() {
        //userLocalStore.clearUserData();
        userLocalStore.setUserLoggedIn(false);
        userLocalStore.deleteCurrentUser();
        super.onStop();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(userLocalStore.getUserLoggedIn()) {
            user=userLocalStore.getLoggedInUser(userLocalStore.getCurrentUser());   
            int i=0;

            //How to change elements in the header programatically
            View headerView = navigationView.getHeaderView(0);
            TextView emailText = (TextView) headerView.findViewById(R.id.mail_header);
            emailText.setText(user.getMail());
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_acc) {
            // Handle the camera action
            loadSelection(0);
        } else if (id == R.id.nav_param) {

        } else if (id == R.id.nav_param_compte) {
            loadSelection(1);

        } else if(id==R.id.logOut){
            userLocalStore.setUserLoggedIn(false);
            userLocalStore.deleteCurrentUser();
            startActivity(login);

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.menu_calendar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        return super.onOptionsItemSelected(item);
    }

    public static User getUser() {
        return user;
    }

    public static UserLocalStore getUserLocalStore() {
        return userLocalStore;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    /*public void setEventNameText(String name) {
        this.eventName.setText(name);
    }

    public void setEventPlaceText(String place) {
        this.eventName.setText(place);
    }

    public void setEventScheduleText(String schedule) {
        this.eventName.setText(schedule);
    }*/

    /*@Override
    public Dialog onCreateDialog (int id) {
        Dialog box = null;

        switch(id) {
            // Quand on appelle avec l'identifiant de la boîte normale
            case ID_NORMAL_DIALOG:
                box = new Dialog(this);
                box.setTitle("Je viens tout juste de naître.");
                break;
            // Quand on appelle avec l'identifiant de la boîte qui s'énerve
            case ID_ENERVEE_DIALOG:
                box = new Dialog(this);
                box.setTitle("ET MOI ALORS ???");  
        }   
        return box;
    }

    @Override
    public void onPrepareDialog (int id, Dialog box) {
        if(id == ID_NORMAL_DIALOG && compteur > 1)
            box.setTitle("On est au " + compteur + "ème lancement !");

        //On ne s'intéresse pas au cas où l'identifiant vaut 1, puisque cette boîte affiche le même texte à chaque lancement

    }*/
}

Settings_accountFragment.java:

public class Settings_accountFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    Button b;
    View v;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Settings_accountFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static Settings_accountFragment newInstance(String param1, String param2) {
        Settings_accountFragment fragment = new Settings_accountFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        v=inflater.inflate(R.layout.fragment_settings_account, container, false);
        b=(Button)v.findViewById(R.id.button);
        b.setOnClickListener(this);
        return inflater.inflate(R.layout.fragment_settings_account, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.button:
                Log.d("coucou","true");
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

fragment_settings_account.xml:

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/parametre_compte"
        android:background="@color/grey"
        android:gravity="center"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_gravity="center_horizontal" />

</FrameLayout>

2 个答案:

答案 0 :(得分:0)

您没有显示包含您设置点击侦听器的按钮的正确视图,因为您再次对视图进行充气并在onCreateView()中将其返回。

替换

return inflater.inflate(R.layout.fragment_settings_account, container, false);

使用

return v;

这样您就可以返回已经膨胀的视图。

答案 1 :(得分:0)

Settings_accountFragment:onCreateView中,您要对视图进行两次充气。删除第二个充气代码,只需return v;

v=inflater.inflate(R.layout.fragment_settings_account, container, false);
b=(Button)v.findViewById(R.id.button);
b.setOnClickListener(this);
return v;

另外,附注 - 在Java class names中使用'_'并不常见。 SettingsAccountFragment优于Settings_accountFragment