setViewRefs(view)和view.findViewById错误

时间:2016-03-07 17:04:41

标签: java android

下面的代码在按下按钮时运行sh文件

package com.me.me.bk;
import com.me.me.R;

import android.app.Fragment;
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.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View.OnClickListener;



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

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

    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  executeScript() {
    button = (Button)view.findViewById(R.id.button);
  try {
    ProcessBuilder pb = new ProcessBuilder(
      "/sdcard/test.sh");
    Process p = pb.start();     // Start the process.
    p.waitFor();                // Wait for the process to finish.
    System.out.println("Script executed successfully");
  } catch (Exception e) {
    e.printStackTrace();
  }
}

 }

但是我在构建APK时遇到此错误

  

/home/nikan/mep/Android_GUI/src/com/me/me/bk/BkFragment.java:50:   错误:找不到符号setViewRefs(view); ^符号:
  方法setViewRefs(View)location:class BkFragment   /home/nikan/mep/Android_GUI/src/com/me/me/bk/BkFragment.java:56:   错误:找不到符号       button =(Button)view.findViewById(R.id.button);                        ^符号:变量视图位置:类   BkFragment 2错误

正如您在我的代码中看到的那样。我导入了视图,但是我收到了这个错误。

1 个答案:

答案 0 :(得分:1)

视图对象都不是全局的,因此您无法从其他方法访问。 其次,根据错误日志没有setViewRefs定义。

更新

试试这个

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

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

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);

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           executeScript();
        }
    });
}

private void  executeScript() {
 try {
    ProcessBuilder pb = new ProcessBuilder(
     "/sdcard/test.sh");
    Process p = pb.start();     // Start the process.
    p.waitFor();                // Wait for the process to finish.
    System.out.println("Script executed successfully");
 } catch (Exception e) {
    e.printStackTrace();
    }
  }
}