旋转器中的ANDROID适配器

时间:2014-05-07 08:33:00

标签: android spinner android-arrayadapter android-spinner

我对使用微调器和适配器有一点疑问,我想搜索目录中的所有文件,并将文件的名称放在微调器中。 这是我的代码:

File repertoire = new File(Environment.getExternalStorageDirectory()+"/androidtest/vente")  ;


    String[] tabFile = repertoire.list();

    if (tabFile==null){

        Log.d("file null","testdfed");  
    }
    Log.d("//","///////////");
    for (int i = 0; i < tabFile.length; i++) {
        Log.d("Tableau",tabFile[i].toString());
    }

    ArrayList<String> list = new ArrayList<String>();
    for(int i=0; i<tabFile.length; i++) {
        list.add(tabFile[i]);

    }

//for checking in the logcat if my code have found all the files        
   for (String s : list) {

       Log.d("Liste",s);
   }


//creation of the adapter   
    ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,
            android.R.layout.simple_spinner_item, list);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp.setAdapter(adapter);

//finally the listener
    sp.setOnItemSelectedListener(new OnItemSelectedListener() {

    public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
        int item = sp.getSelectedItemPosition();
        Toast.makeText(getBaseContext(),
                "You have selected 222 : " + item,
                Toast.LENGTH_SHORT).show();

    }
    public void onNothingSelected(AdapterView<?> arg0) { }
});

我的代码在sp.setAdapter(适配器)崩溃; 谢谢 ! :)

我是SOF的新手,我必须编辑我的文字: 对于穆克什库马尔的答案 已经完成,我在onCreate之前初始化

public class OfflineActivity extends FragmentActivity {

private PagerAdapter mPagerAdapter;
private Spinner sp = (Spinner)findViewById(R.id.spinm);

protected void onCreate(Bundle savedInstanceState) {

所以我会像你一样替换

public class OfflineActivity extends FragmentActivity {

private PagerAdapter mPagerAdapter;
private Spinner sp;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setContentView(R.layout.viewpager);
    sp = (Spinner)findViewById(R.id.spinm);
由于同样的原因,我的代码崩溃了:/

3 个答案:

答案 0 :(得分:0)

正如你所说My code crash at sp.setAdapter(adapter);

您可能尚未初始化sp ,.首先初始化它以供使用。即 在onCreate()的{​​{1}}中写下此代码。

Activity

答案 1 :(得分:0)

这适用于微调器

spinner1 = (Spinner) findViewById(R.id.spinner1);
    List<String> list = new ArrayList<String>();
    list.add("Android");
    list.add("Java");
    list.add("Spinner Data");
    list.add("Spinner Adapter");
    list.add("Spinner Example");

    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(dataAdapter);

答案 2 :(得分:0)

这可能是因为您传递片段而不是上下文尝试替换ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, list);

ArrayAdapter<String> adapter = new ArrayAdapter<String> (getActivity(),
        android.R.layout.simple_spinner_item, list);