我有一个 Drawscreen.class 文件,主要活动和 Drawthegraph.class 扩展了视图。我在 Drawthegraph.class 中有一个方法,我需要从 Drawscreen.class 调用。我可以这样做吗? 的 Drawscreen.class -
public class Drawscreen extends ActionBarActivity
{
//LinearLayout linear=(LinearLayout)findViewById(R.id.main_layout);
//draw=(Drawthegraph)findViewById(R.id.main_layout);
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
ActionBar actionbar=getSupportActionBar();
actionbar.show();
View drawthegraph=new Drawthegraph(this);
setContentView(drawthegraph);
drawthegraph.setBackgroundColor(color.Ivory);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.drawscreen, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
case R.id.undo:/*Call method of view here*/
break;
}
return super.onOptionsItemSelected(item);
}
}
Drawthegraph.class
public class Drawthegraph extends View
{
private int lines;
----
----
public void decrease_lines() /*Call this function from Drawscreen*/
{
if(lines>0)
{
lines--;
}
}
答案 0 :(得分:1)
将drawthegraph
变量用作实例字段:
public class Drawscreen extends ActionBarActivity
{
//LinearLayout linear=(LinearLayout)findViewById(R.id.main_layout);
//draw=(Drawthegraph)findViewById(R.id.main_layout);
private Drawthegraph drawthegraph;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
ActionBar actionbar=getSupportActionBar();
actionbar.show();
this.drawthegraph=new Drawthegraph(this);
setContentView(drawthegraph);
drawthegraph.setBackgroundColor(color.Ivory);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.drawscreen, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
case R.id.undo:/*Call method of view here*/
drawthegraph.decrease_lines();
break;
}
return super.onOptionsItemSelected(item);
}
}
答案 1 :(得分:1)
您的Drawthegraph对象必须是您的Activity的字段:
public class Drawscreen extends ActionBarActivity {
Drawthegraph drawthegraph;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
...
drawthegraph = new Drawthegraph(this);
setContentView(drawthegraph);
drawthegraph.setBackgroundColor(color.Ivory);
}
...
然后你可以在Drawscreen中的任何地方打电话:
drawthegraph.decrease_lines();