按钮单击无法在Fragment中工作

时间:2017-01-14 04:00:03

标签: java android

我想在片段按钮上单击显示activity_main。

我的代码有问题吗?

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    myView = inflater.inflate(R.layout.splash, container, false);

   Button smart1 = (Button) myView.findViewById(R.id.smart1);
    smart1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
           getActivity().onBackPressed();

        }

    });


    return myView;
}

按钮不起作用。它只是停留在同一页面上,没有任何反应。

为Nas编辑

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Toast;
import android.view.View.OnClickListener;


public class Splash extends Fragment {

    View myView;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.splash, container, false);

        return myView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Button smart1 = (Button) view.findViewById(R.id.smart1);
        smart1.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
                getActivity().onBackPressed();

        }

        });


    }
}

这是Splash.java,为什么按钮不起作用很奇怪。提前谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个

@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    Button smart1 = (Button) view.findViewById(R.id.smart1);
    smart1.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v){
       getActivity().onBackPressed();

    }

});