我正在尝试根据微调器中选择的项目设置textView的文本。但它始终显示else语句的值。有人可以帮我解决这个问题。 代码如下。
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] names = {"Shashank","Abhijay"};
String[] state_array = {"Select City","Bangalore","Jaipur"};
setContentView(R.layout.activity_main);
Spinner spinner_state = (Spinner)findViewById(R.id.spinner1);
spinner_state.setAdapter((SpinnerAdapter) new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
state_array ));
if(spinner_state.equals(state_array[1]))
{
TextView candi_name = (TextView) findViewById(R.id.CandidateName);
candi_name.setText(names[0]);
}
if(spinner_state.equals(state_array[2])){
TextView candi_name = (TextView) findViewById(R.id.CandidateName);
candi_name.setText(names[1]);
}
else{
TextView candi_name = (TextView) findViewById(R.id.CandidateName);
candi_name.setText(" ");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
答案 0 :(得分:0)
使用onItemSelectedListener
spinner_state.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
答案 1 :(得分:0)
如果条件为:
,请更换您的微调器 // your code above...
if(spinner_state.getSelectedItem().toString().equals(state_array[1]))
{
TextView candi_name = (TextView) findViewById(R.id.CandidateName);
candi_name.setText(names[0]);
}
if(spinner_state.getSelectedItem().toString().equals(state_array[2])){
TextView candi_name = (TextView) findViewById(R.id.CandidateName);
candi_name.setText(names[1]);
}
else{
TextView candi_name = (TextView) findViewById(R.id.CandidateName);
candi_name.setText(" ");
}
//your code below
答案 2 :(得分:0)
您需要使用onItemSelectedListener()来捕获选定的微调器项。在微调器初始化之后添加以下代码并删除if / else语句:
spinner_state.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
if(spinner_state.getSelectedItem().toString().equals(state_array[1]))
{
TextView candi_name = (TextView) findViewById(R.id.CandidateName);
candi_name.setText(names[0]);
}
if(spinner_state.getSelectedItem().toString().equals(state_array[2]))
{
TextView candi_name = (TextView) findViewById(R.id.CandidateName);
candi_name.setText(names[1]);
}
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
TextView candi_name = (TextView) findViewById(R.id.CandidateName);
candi_name.setText(" "); }
});