如何从OnItemSelected中获取变量父项并在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
}
}
答案 0 :(得分:0)
您只需要将变量声明为数据成员,就像您已声明test_array
,display
和selected
而不是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.