-1

如何从 OnItemSelected 中获取变量 parent 并在 onClick 中使用它?我要在 onClick 中执行此操作

result = parent.getItemAtPostition(pos).toString();
selected = (TextView) findViewById(R.id.selected);
selected.setText(result);

当我单击按钮时,我希望该结果显示在选定的文本视图中。结果将是微调器中的选定项目。这是第一次使用微调器,所以我不知道。

MainActivity.java

package com.example.test;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity implements OnItemSelectedListener{

String[] test_array;
TextView display, selected;
Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.test_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    submit = (Button) findViewById(R.id.submit);
    submit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            parent.getItemAtPosition(pos).toString();

        }
    });
}
        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int pos, long id) {
            selected = (TextView) findViewById(R.id.selected);
            String result;
            // TODO Auto-generated method stub
            result = parent.getItemAtPosition(pos).toString();




        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }

}

4

1 回答 1

0

您只需要将变量声明为数据成员,即就像您声明的一样test_arraydisplayselected不是在onItemSelected方法内部。

public class MainActivity extends Activity implements OnItemSelectedListener
{

   String[] test_array;
   TextView display, selected;
   Button submit;
   String result;   // <------- declare the variable here and you can access it through out the activity/class.
于 2013-03-26T13:51:25.760 回答