繁体   English   中英

在NavigationDrawer中单击按钮即可打开活动

[英]Open activity on button click in NavigationDrawer

我已经在Android Studio中使用Navigation Drawer Activity创建了项目,并且已经成功创建了该项目。在Navigation抽屉活动中,我创建了3部分,在第1部分中,我将Button放置在按钮上,并且我想在该按钮上设置setOnClickListener方法,以启动新的Activity(例如“ xyz.class”)我使用过代码

startActivity(new Intent(this,xyz.class));

但是“ this”关键字无法正常工作,并给我错误。 因此,我将代码更改为

Context c; startActivity(new Intent(c,xyz.class));

给出了NullPointerException,

我的Section1代码是

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.example.pratik.crm50.R;
import com.gc.materialdesign.views.ButtonFloat;
public class Dashboard extends Fragment implements View.OnClickListener {
    View rootView;
    Context c;
    private ButtonFloat float_btn;
    private Button but;
    private Button btn;
    Context c;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        View v;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            v = inflater.inflate(R.layout.dashboard_layout,container, false);
        } else {
            v = super.onCreateView(inflater,container, savedInstanceState);
        }
      View vv=v.findViewById(R.id.button_simple);
        vv.setOnClickListener(this);
        return v;
    }
    @Override
    public void onClick(View v) {
       // Toast.makeText(c,"Float Button",Toast.LENGTH_SHORT).show();
        Log.e("ssas","sasafa");
        //startActivity(new Intent(c,xyz.class));
    }

}

并且我可以成功在上面的代码中登录Log.e("ssas","sasafa") 那么该怎么做呢?

Intent构造函数期望第一个参数正是Fragment时,Fragment不会扩展Context

Context c变量是多余的,因为Fragment默认情况下会保存父活动。

您需要使用该片段附加到的活动(扩展Context类):

startActivity(new Intent(getActivity(), xyz.class));

您将收到NullPointerException ,因为您从未将值赋给Context c 因此,正如user3249477所提到的,使用方法getActivity()为c分配一个值,例如c=getActivity(); 或在启动Intent时直接调用它。 看起来像这样: startActivity(new Intent(getActivity(),xyz.class));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM