【问题标题】:Open activity on button click in NavigationDrawer在导航抽屉中单击按钮时打开活动
【发布时间】:2015-02-01 09:58:02
【问题描述】:

我已经在 Android Studio 中创建了带有 Navigation Drawer Activity 的项目,并且我已经成功创建了它,在导航抽屉活动中我创建了 3 个部分,在第一个部分中我放置了 Button,我想在那个导致启动的按钮上设置 setOnClickListener 方法新活动(例如“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")。 那么如何做到这一点呢?

【问题讨论】:

  • 为什么要定义 Context c 两次?
  • 使用新的 Intent(getActivity(),xyz.class)

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


【解决方案1】:

片段不扩展Context,而Intent 构造函数期望第一个参数正是这样。

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

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

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

【讨论】:

    【解决方案2】:

    你会得到一个NullPointerException,因为你永远不会为Context c 赋值。 因此,正如 user3249477 也提到使用方法 getActivity() 为 c 赋值,如 c=getActivity(); 或者在启动 Intent 时直接调用它。这看起来像这样:startActivity(new Intent(getActivity(),xyz.class));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多