gpt4 book ai didi

java - 创建可重用类

转载 作者:行者123 更新时间:2023-11-29 23:24:32 24 4
gpt4 key购买 nike

我有一个在 Android 中运行的应用程序,我想创建一个菜单并在某些 Activity 中重复,该菜单调用 Intent 以打开其他 Activity 。

我该怎么做?

我想也许我可以创建一个类,但我遇到了错误。我在哪里可以为此创建一个类?是否在 onCreate 方法内部?我怎样才能在另一个 Activity 中重复使用菜单?

谢谢!!

这是我的菜单代码:

menu_button = (Button) findViewById(R.id.menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this, menu_button);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());

popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Intent vista = new Intent(MainActivity.this, openCamera.class);
MainActivity.this.startActivity(vista);

}
return true;

/*
Toast.makeText(MainActivity.this, "" + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
*/
}
});
popupMenu.show();
}
});

最佳答案

如果菜单总是一样的,并且你想在多个 Activity 中重复使用它,你只需像这样定义它:

public class TestMenu {

private final PopupMenu popupMenu;

public TestMenu(final Activity activity, View anchor) {
popupMenu = new PopupMenu(activity, anchor);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());

popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Intent vista = new Intent(activity, openCamera.class);
activity.startActivity(vista);
}
return true;
}
});
}

public void show() {
popupMenu.show();
}
}

然后像这样在您的 Activity 中使用它:

public class TestActivity extends Activity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Button menu_button = (Button) findViewById(R.id.menu_button);
TestMenu myMenu = new TestMenu(this, menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myMenu.show();
}
});
}
}

关于java - 创建可重用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53761535/

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