2017-02-28 88 views
0

我中創建了一個字符串項工具欄中簡單的微調添加到工具欄微調,我不需要在這個string.xml項目,我只是想通過Java代碼添加項目 我只是希望項目動態添加到工具欄微調從數據庫中選擇的形式採取了這些項目,這是我的活動代碼如何將項目動態android系統

package abtech.waiteriano.com.actionbartest; 

import android.os.Build; 
import android.os.Bundle; 
import android.support.annotation.RequiresApi; 
import android.support.v7.app.AppCompatActivity; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.Spinner; 
import android.widget.SpinnerAdapter; 
import android.widget.Toast; 

public class MainActivity extends AppCompatActivity { 
    private android.support.v7.widget.Toolbar toolbar; 
    private String[] category = {"hello", "this", "is", "me"}; 

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     category = getResources().getStringArray(R.array.category); 
     toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     getSupportActionBar().setDisplayShowTitleEnabled(false); 
//  toolbar.setLogo(R.mipmap.ic_launcher); 
     SpinnerAdapter spinnerAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.category, R.layout.spinner_dropdown_item); 
     Spinner navigationSpinner = new Spinner(getSupportActionBar().getThemedContext()); 
     navigationSpinner.setAdapter(spinnerAdapter); 
     toolbar.addView(navigationSpinner, 0); 
     navigationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
      @Override 
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
       Toast.makeText(MainActivity.this, 
         "you selected: " + category[position], 
         Toast.LENGTH_SHORT).show(); 
      } 

      @Override 
      public void onNothingSelected(AdapterView<?> parent) { 

      } 
     }); 
    } 
} 

回答

0

您可以添加字符串數組直接進入到ArrayAdapter象下面這樣:

private String[] category = {"hello", "this", "is", "me"}; 

Spinner navigationSpinner = new Spinner(getSupportActionBar().getThemedContext()); 
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, category); 
navigationSpinner.setAdapter(adapter); 
+0

感謝您的回答,但我在這裏有同樣的問題它只顯示它em,它在string.xml中不在私有String [] category = {「hello」,「this」,「is」,「me」}; – 7arooney

+0

對不起,我現在編輯一些東西,它很好地工作,非常感謝 – 7arooney

相關問題