-1

我有个问题。我不知道如何调用不同的类。该代码用于一个按钮(当您单击该按钮时,一条消息随机出现)所以我认为如果我将它放在不同的类中会更好,因为我也使用过数组。现在我不知道如何调用该类.

这是我的代码。我想在 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);
    }
}
4

1 回答 1

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()创建该类的实例并执行该方法。

于 2013-10-15T17:37:13.897 回答