如果所有代码都在MainActivity中但不包含两个类,则代码可以工作

时间:2017-09-17 12:32:08

标签: android class android-arrayadapter android-spinner

我有两个类MainActivity和WordBase。代码不起作用,但是当我将它从WordBase类复制到MainActivity时,它可以正常工作。 这是两个类

public class WordsBase {
private Activity context=null;
private View myView;

//  Type of words that user wants to search
private final String Noun="Nomen",Adjectives="Adjectives",Verbs="Verben";


 public WordsBase(Activity context)
     {
        this.context= context;
    }

     // creat the list menu that lets User to choose what type of words wants to search
    public void create () {

       LayoutInflater inflater = context.getLayoutInflater();
        myView = inflater.inflate(R.layout.words_base, null);
       Spinner sp1 = (Spinner) myView.findViewById(R.id.spinner1);

       List<String> arr = new ArrayList<String>();
       arr.add(Noun);
       arr.add(Adjectives);
       arr.add(Verbs);

       ArrayAdapter<String> menu_Adapter = new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,arr);
       sp1.setAdapter(menu_Adapter);

   }

}

这是MainActivity

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.words_base);
    WordsBase menu =new WordsBase(this);
    menu.create();

   }
}

1 个答案:

答案 0 :(得分:-1)

您忘记将视图添加到主要活动。

你可以像这样返回视图

public view create(){

...  返回myView; }

并在主要活动中获得外部relativelayout layout.addview(menu.create());