[英]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.