【问题标题】:Finding the current layout-xml file in focus using code使用代码查找当前的 layout-xml 文件
【发布时间】:2013-06-27 06:51:43
【问题描述】:

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

谢谢。

【问题讨论】:

    标签: android view android-activity polymorphism


    【解决方案1】:

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

    【讨论】:

    • 是的,但这不是很多态。有多种方法可以解决问题,但我想只用一种方法。
    • 不,它非常多态——它在 UI 上是多态的。
    【解决方案2】:

    除了Gabe's answergetCurrentFocus()不会给你activity的布局。如果想要activity的布局,可以使用

    View v = (View)findViewById(android.R.id.content);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-11
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 2019-05-12
      相关资源
      最近更新 更多