gpt4 book ai didi

java - 制作按钮时,在范围内无法访问类型 MainActivity 的封闭实例

转载 作者:行者123 更新时间:2023-11-29 21:08:55 25 4
gpt4 key购买 nike

在尝试制作安卓应用程序时,我遇到了错误:MainActivity 类型的封闭实例在范围内不可访问Toast.makeText(MainActivity.this, "Swag", Toast.LENGTH_SHORT).show();

这是我的 MainActivity.java:

public class MainActivity extends ActionBarActivity {
static Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements View.OnClickListener {

public PlaceholderFragment() {
}

@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Swag", Toast.LENGTH_SHORT).show();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.fragment_main, container,false);
btn=(Button) rootView.findViewById(R.id.test_button);
btn.setOnClickListener(this);
return rootView;
}
}
}

最佳答案

您必须在 fragment 中使用 getActivity()。

请注意,如果您正在执行某些后台作业,或返回时执行任何其他异步任务,则 getActivity() 可能为 null。所以每次使用它时都检查是否为 null。

关于 fragment 的更多信息,可以使用this .

关于java - 制作按钮时,在范围内无法访问类型 MainActivity 的封闭实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23588638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com