【问题标题】:How to identify if a view is Button or Textview如何识别视图是 Button 还是 Textview
【发布时间】:2014-05-15 03:32:14
【问题描述】:

我有一个错误函数,它将View 作为输入,并通过将其背景更改为红色来显示错误,而视图的值有任何问题,如下所示 -

public static void error(View v) {
        v.setBackgroundResource(android.R.color.holo_red_light);

    }

我在另一个函数中使用这个函数,我以这种方式使用它 -

public static void nonEmptyNonZero(View v) {
    String check = "";
    check = ((TextView) v).getText().toString();
    if ((check.equals(null)) || check.equals("0") || check.equals("")) {
        error(v);
    }
}

我的问题是,v 可以是任何东西(TextView、EditText)。那么如何识别视图的类型是什么。这样我就可以使用正确的转换,同时使用 -

check = ((TextView) v).getText().toString();

PS - 我已经用过instanceOf,我不确定View 的投射效果如何。

【问题讨论】:

  • 你可能只是偷偷摸摸,然后通过 try catch 投射到按钮上,这将是 textview (假设它总是一个或另一个)但有更好的方法。
  • instanceOf 不应该工作吗? *View extends View.
  • v.getClass().getName() 将以字符串形式返回视图类型。
  • 如果您确定视图包含文本(EditText、Button 或 TextView),您可以将此视图转换为 TextView,因为 EditText(和 Button)正在扩展 TextView。接下来你可以使用 getText() 方法

标签: android view textview instanceof


【解决方案1】:

喜欢你在对象列表中的视图

List<Object> objectViews=new ArrayList();

观看次数

EditText txtEditText=new EditText();
TextView txtTextView=new TextView();
objectViews.add(txtEditText); 
objectViews.add(txtTextView); 

遍历查找对象(视图)

Object view=new Object();
for(int i=0;i<objectViews.size;i++)
{
   view.get(i);
   if(view instanceof EditText)
    {
      Log.e("EditText","value="((EditText) view).getText());
    }
else if(view instanceof TextView)
    {
      Log.e("TextView","value="((TextView) view).getText());
    }
}

【讨论】:

    猜你喜欢
    • 2010-10-26
    • 2014-11-08
    • 2018-10-28
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 2015-10-05
    相关资源
    最近更新 更多