我在项目中使用了this answer by Jared Rummler中的代码,以下代码就是结果。
public class MainActivity extends Activity {
Button dadclink;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public Intent addListenerOnButton() {
dadclink = (Button) findViewById(R.id.dadclink);
public static Intent newInstagramProfileIntent(PackageManager pm, String url) {
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
if (pm.getPackageInfo("com.instagram.android", 0) != null) {
if (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
String natgeo = url.substring(url.lastIndexOf("/") + 1);
intent.setData(Uri.parse("http://instagram.com/_u/" + natgeo));
intent.setPackage("com.instagram.android");
return intent;
}
} catch (NameNotFoundException e) {
}
intent.setData(Uri.parse(url));
return intent;
}};
但是,我在这一行上遇到语法错误:
public static Intent newInstagramProfileIntent(PackageManager pm, String url) {
出现以下错误:
- 参数newInstagramProfileIntent的非法修饰符;只允许决赛
- 令牌上的语法错误“,”,;预期
- 令牌上的语法错误“)”,;预期
如何解决这个问题?
答案 0 :(得分:0)
你不能在函数内部有函数声明。
public Intent addListenerOnButton() {
dadclink = (Button) findViewById(R.id.dadclink);
// illegal operation
public static Intent newInstagramProfileIntent(PackageManager pm, String url) {
...
}
};
相关:Function within function in Java
如果我理解你想做什么,你想创建一个按钮的监听器,点击时使用 Instagram Intent
。代码应修改为:
public void addListenerOnButton() {
dadclink = (Button) findViewById(R.id.dadclink);
dadclink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = newInstagramProfileIntent(getPackageManager(),
"your_string_url");
// do something with the intent, perhaps starting an activity
startActivity(intent);
}
});
}
public static Intent newInstagramProfileIntent(PackageManager pm, String url) {
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
if (pm.getPackageInfo("com.instagram.android", 0) != null) {
if (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
String natgeo = url.substring(url.lastIndexOf("/") + 1);
intent.setData(Uri.parse("http://instagram.com/_u/" + natgeo));
intent.setPackage("com.instagram.android");
return intent;
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
intent.setData(Uri.parse(url));
return intent;
}