1

我正在做一个练习 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);
    }
}

谢谢。

4

2 回答 2

0

除了Gabe 的回答getCurrentFocus()不会给你活动的布局。如果你想要活动的布局,你可以使用

View v = (View)findViewById(android.R.id.content);
于 2013-06-27T07:03:16.160 回答
0

这不是这样做的方法。如果您希望他们做不同的事情,请参考不同的点击处理程序。如果它们差异很大,它们甚至不应该具有相同的 id。自动布局覆盖背后的整个想法是应用程序永远不需要关心使用哪一个。

于 2013-06-27T06:56:56.463 回答