按钮findViewById()出错

时间:2016-03-05 15:42:36

标签: java android button io

我想在我的应用中添加一个页面,它包含一个按钮 但它面临这个错误

 /src/com/me/my/bk/BkFragment.java:57: error: cannot find symbol
        button = (Button) findViewById(R.id.button);

起初我解决了9个错误,现在我有这个错误,这是我的代码:

   package com.me.my.bk;

import com.me.my.R;
import android.app.Fragment;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;

public class BkFragment extends Fragment {
    public static final String TAG = BkFragment.class.getSimpleName();

    public static BkFragment newInstance() {
        return new BkFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_bk, container, false);
    }

    private Button button;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
            @SuppressLint("SdCardPath")
            @Override
            public void onClick(View arg0) {
                Process p=null;
                try {
                    p = new ProcessBuilder()
                    .command("/sdcard/test.sh")
                    .start();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(p!=null) p.destroy();
                }
            }
        });
    }
}

我遇到此错误的任何解决方案? 提前谢谢

2 个答案:

答案 0 :(得分:0)

您应该在onCreateView上执行不在onCreate

中的所有操作
 View a = inflater.inflate(R.layout.fragment_bk, container, false);

 listView = (ListView) a.findViewById(R.id.button);

答案 1 :(得分:0)

确定。这段代码应该有用。

 private Button button;         
 @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View view  = inflater.inflate(R.layout.fragment_bk, container, false);
    setViewRefs(view);
    return view;
}


private void setViewRefs(View view){
     button = (Button)view.findViewById(R.id.button);

  }