如何在android中调用另一个类?

时间:2013-10-15 17:32:08

标签: android clicklistener

我有问题。我不知道如何打电话给另一个班级。代码是一个按钮(当你点击按钮时,一条消息随机出现)所以我认为如果我将它放在一个不同的类中会更好,因为我也使用过数组。现在我不知道如何调用该类

这是我的代码。我想在SecondActivity中调用“Firstin”。

public class SecondActivity extends Activity {
private Firstin mFirst = new Firstin ();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        //finds textview

        final Text Ftext = (Text) findViewById(R.id.textView2);
        @SuppressWarnings("unused")
        final Text Stext = (Text) findViewById(R.id.textView3);
        //finds button view
        Button btnView = (Button) findViewById(R.id.button1);
        @SuppressWarnings("unused")
        Button btnView2 = (Button) findViewById(R.id.button2);

        btnView.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {




String Answer = mFirst.firstAnswer();

                Ftext.setTextContent(Answer);
            }
        });

这是我试图打电话的课程:

package com.example.insultgenerator;

import java.util.Random;

public class Firstin {
public String firstAnswer(){
    String [] mResults={
            "its cool",
            "we cool",
            "im cool",
            "he cool",
            "she cool"
            };
    // the button was clicked so replace the answer label with answer
    String Answer = "" ;
    // the two double is a 'empty string 
    Random RandomGen = new Random();// telling the program to construct a random generator
    int RandomNum= RandomGen.nextInt(mResults.length);

    Answer = mResults[RandomNum];
    return(Answer);
    }
}

1 个答案:

答案 0 :(得分:1)

你应该转为TextView

        final TextViewFtext = (TextView) findViewById(R.id.textView2);
        @SuppressWarnings("unused")
        final TextViewStext = (TextView) findViewById(R.id.textView3);

然后使用TextView.setText(...)方法:

String Answer = mFirst.firstAnswer();

                Ftext.setText(new Firstin().firstAnswer());
            }
        });

然后最后使用new Firstin().firstAnswer()从另一个类调用该方法,该类创建该类的实例并执行该方法。