需要帮助修复我的项目的输出

时间:2012-04-17 13:55:01

标签: java android eclipse

int department;
Button search;
String display;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    department = 0;
    search = (Button) findViewById(getResources().getIdentifier("btnSearch", "id",    getPackageName()));
    display = (String) findViewById(getResources().getIdentifier("tvDisplay", "id",      getPackageName()));

    search.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (department == 1)
            {
                display = "food";
            }

我要做的是让一个用户输入一个数字,点击一个按钮,它将在我底部的textView上显示一个部门名称。但是,我有错误,我已经将它的几个部分转换为字符串而不是textView。我如何修复输出的位置?

display = (String) findViewById(getResources().getIdentifier("tvDisplay", "id", getPackageName()));说它无法从View转换为String。

3 个答案:

答案 0 :(得分:2)

试试这个:

TextView display = (TextView) findViewById(getResources().getIdentifier("tvDisplay", "id", getPackageName()));

// get the text
String displayString = (String)display.getText();

答案 1 :(得分:2)

问题是您正在将textview转换为字符串。您应该将display的类型更改为TextView,并使用其setText方法在其中显示文字,请尝试以下代码:

int department;
Button search;
TextView display;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    department = 0;
    search = (Button) findViewById(getResources().getIdentifier("btnSearch", "id", getPackageName()));
    display = (TextView) findViewById(getResources().getIdentifier("tvDisplay", "id", getPackageName()));

    search.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            if (department == 1)
            {
                display.setText("food");
            }
        }
    });
}

答案 2 :(得分:0)

tvDisplay是TextView,而不是String。因此,显示一个TextView,找到视图,然后调用display.getText()来获取显示的文本。