下面的代码在按下按钮时运行一个 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: error: cannot find symbol setViewRefs(view); ^ symbol:
method setViewRefs(View) location: class BkFragment /home/nikan/mep/Android_GUI/src/com/me/me/bk/BkFragment.java:56: error: cannot find symbol button = (Button)view.findViewById(R.id.button); ^ symbol: variable view location: class BkFragment 2 errors
如您在我的代码中所见。我已经导入了 View ,但我收到了这个错误。
最佳答案
View 对象都不是全局的,因此您不能从其他方法访问。 其次,没有根据错误日志定义的 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();
}
}
}
关于java - setViewRefs(view) 和 view.findViewById 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35849649/