我正在做一个练习 android 项目,我正在尝试将多态性想法实现到我的程序中。到目前为止,我已经创建了两种不同的 XML 布局,一种用于平板电脑,一种用于手机。他们都有一个按钮,但我希望按钮根据它所在的布局执行不同的操作。我使用的是 onClick 属性,两个布局的按钮都引用相同的方法。
在我的 buttonClick 方法中,我想找出当前正在显示哪个布局,我正在尝试这样做,
public void buttonClick(View ve)
{
View v = getCurrentFocus();
//According to the API, this method returns the current view,
//but the Log Tag says that it is null, which should not be the case.
Log.i(TAG, "Current View is " + v.getContentDescription());
//I want to control what happens polymorphically using the next if-else
//clause,depending on the layout, I think that this part would work if
//the above code works alright.
if(v.getId() == R.id.TabletLayout)
{
TextView myText = (TextView)findViewById(R.id.textView);
if(myText.getText().toString().contains("World"))
myText.setText(R.string.ayo_android);
else
myText.setText(R.string.hello_world);
Log.i(TAG, "changing words");
}
else{
Log.i(TAG, "Creating new Activity");
myText = (TextView)findViewById(R.id.textView);
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("screenText", myText.getText().toString());
startActivity(intent);
}
}
谢谢。