我有一个主要的活动,当我按下一个按钮时,我导航到一个滑动选项卡视图.现在我希望在这些选项卡中有一个可点击按钮,并在按下按钮时显示一个Toast.这是我使用的代码:

import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.Button;

public class laundry extends Fragment {

Button btn_service;

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

// TODO Auto-generated method stub

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

btn_service = (Button) findViewById(R.id.btn_service);

btn_service.setOnClickListener(this);

}

但findViewById不是此活动的已知符号.是否有另一种方法可以在上面的片段活动中加入可点击按钮?

跑了项目,我得到了这个错误. (我不知道建议的更改是否有效,我的应用程序崩溃了以下错误)这是一个片段活动,我试图在单击按钮时生成一个Toast.

public class in_room_dining extends Fragment

{

Button btn_order;

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState)

{

// TODO Auto-generated method stub

btn_order.setOnClickListener(new OnClickListener()

{

public void onClick(View v)

{

Toast.makeText(getActivity(), "text", Toast.LENGTH_SHORT).show();

}

});

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

}

}

我得到的错误是:

11-29 10:57:42.820 938-938/com.appt.shreyabisht.staymax E/AndroidRuntime﹕ FATAL EXCEPTION: main

Process: com.appt.shreyabisht.staymax, PID: 938

java.lang.NullPointerException

at com.appt.shreyabisht.staymax.in_room_dining.onCreateView(in_room_dining.java:23)

at android.support.v4.app.Fragment.performCreateView(Fragment.java:1504)

(in_room_dining.java:23)是btn_order.setOnClickListener(new OnClickListener())

解决方法:

import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.Button;

public class laundry extends Fragment {

Button btn_service;

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

// TODO Auto-generated method stub

final View rootView = inflater.inflate(R.layout.activity_laundry, container,

false);

btn_service = (Button) rootView.findViewById(R.id.btn_service);

btn_service.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

//your Code Goes Here

}

});

return rootView;

}

标签:android,android-fragments,button

来源: https://codeday.me/bug/20190725/1529229.html

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐