目前我有2个活动具有完全相同的视图。但是,单击某个项目时,执行的操作会有所不同。这是多余的,我想只使用1个活动和2个不同的onClick行为。
点击主菜单中的按钮即可访问这两项活动。如何区分单击了哪个按钮并自定义onClick操作?
A.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_identify_animals);
setupActionBar();
GridView gridview = (GridView) findViewById(R.id.gridviewidentify);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "Clicked!", Toast.LENGTH_LONG).show();
}
});
}
B.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_animal);
setupActionBar();
GridView gridview = (GridView) findViewById(R.id.gridviewreport);
gridview.setAdapter(new ImageAdapter(this));
// Set up onClick listener
gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
DialogConfirmation.LaunchNewDialog(B.this, "Title", "Message.", "Action", "Cancel");
}
});
}
答案 0 :(得分:2)
将您的一项活动称为以下内容:
Intent myIntent = new Intent(getApplicationContext() , C.class) ;
myIntent.putExtra("activity" , "A");
startActivity(myIntent);
Intent myIntent = new Intent(getApplicationContext() , C.class) ;
myIntent.putExtra("activity" , "B");
startActivity(myIntent);
然后在你的onCl活动onClickListener中执行以下操作:
String activity = getIntent().getExtras().getString("activity");
if(activity .equals("A") ) {
}else if (activity .equals("B")){
}
并给我一些反馈。
希望能帮助。
答案 1 :(得分:0)
两种功能的内容应分为两个功能,
public void functionA(){
//One functionality here
//increment/decrement your flag
}
public void functionB(){
//Second functionality here
//increment/decrement your flag
}
然后在你的onCLickListener:
private View.OnClickListener onPress = new View.OnClickListener() {
@Override
public void onClick(View v) {
If(flag == somevalue){
functionA();
}else {
functionB();
}
}
};
答案 2 :(得分:0)
在您的通话代码中,添加额外的意图,以指示单击按钮时应采取的操作,例如
intent.putExtra("click_option", 1);
然后在您的活动中,只需检查额外的存在及其值:
Bundle extras = getIntent().getExtras();
if (extras != null & extras.containsKey("click_option")) {
// do something
}