Android ListView setOnItemClickListener(setText Button)不起作用

时间:2015-03-27 22:09:42

标签: android android-studio

我无法在" BarraNome"中设置所选对象的名称。我怎么办?

public class MainActivity2Activity extends Activity {

String[] lista1 = { "JAN", "FEB", "MAR", "APR", "MAY", "JUNE", "JULY","AUG", "SEPT", "OCT", "NOV", "DEC" };

Button BarraNome;
private ListView lista;
private ArrayAdapter arrayAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activity2);

    lista = (ListView) findViewById(R.id.listacompleta);
    arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, lista1);
    lista.setAdapter(arrayAdapter);

    lista.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> av, View v, int pos,long id){

看看这部分代码!

            //This code works//
            Toast.makeText(getApplicationContext(),""+ lista1[pos], Toast.LENGTH_LONG).show();

            //Don't works, why?//
            BarraNome.setText(""+ lista1[pos]);
        }});}}

请帮帮我

2 个答案:

答案 0 :(得分:0)

  1. 下次发布堆栈跟踪。
  2. 根据您发布的内容,您永远不会像这样分配按钮:

    BarraNome =(Button)findViewById(R.id.yourButton);

答案 1 :(得分:0)

    public class MainActivity2Activity extends Activity {

    String[] lista1 = { "JAN", "FEB", "MAR", "APR", "MAY", "JUNE", "JULY","AUG", "SEPT", "OCT", "NOV", "DEC" };

    Button BarraNome;
    private ListView lista;
    private ArrayAdapter arrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity2);
//please intialize button
    **BarraNome=(Button)findViewById(R.id.your_button_id);**
        lista = (ListView) findViewById(R.id.listacompleta);
        arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, lista1);
        lista.setAdapter(arrayAdapter);

        lista.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> av, View v, int pos,long id){

///////////////////然后设置

Toast.makeText(getApplicationContext(),""+ lista1[pos], Toast.LENGTH_LONG).show();

            //Don't works, why?//
            BarraNome.setText(""+ lista1[pos]);
        }});}}