如何选择(例如“ pila 9v”)并打开新屏幕?
这是我的代码,但是当我编写“ pila”时,它将显示在自动完成列表(pila 9v和pila 12v)中,而当我选择“ pila 12v”时,它将带我进入“ pila 9v”活动,因为那是该单词在“字符串”中的第二个位置。
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] values = new String[]{"bateria 9v", "pila 9v", "bateria 12v", "pila 12v"};
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,values);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.txtMercancias);
textView.setThreshold(3);
textView.setAdapter(adapter);
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Item: " + adapter.getItem(position), Toast.LENGTH_SHORT).show();
if (position==0) {
Intent myintent = new Intent(view.getContext(), Main2Activity.class);
startActivityForResult(myintent, 0);
}
if (position==1) {
Intent myintent = new Intent(view.getContext(), Main3Activity.class);
startActivityForResult(myintent, 1);
}
if (position==2){
Intent myintent = new Intent(view.getContext(),Main4Activity.class);
startActivityForResult(myintent,2);
}
if (position==3){
Intent myintent = new Intent(view.getContext(),Main5Activity.class);
startActivityForResult(myintent,3);
}
}
});
}
}
最佳答案
在使用AutoCompleteTextView时,我也遇到了同样的问题,并以此方式解决了这一问题。
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
LinearLayout ll = (LinearLayout) view;
//This will give you the string value of selected list item
TextView listItem = (TextView) ll.getChildAt(0);
//You can do this or apply own logic to find the selected value case
Switch(listItem.getText().toString()) {
case "bateria 9v":
Intent myintent0 = new Intent(view.getContext(), Main2Activity.class);
startActivityForResult(myintent0, 0);
break;
case "pila 9v":
Intent myintent1 = new Intent(view.getContext(), Main3Activity.class);
startActivityForResult(myintent1, 1);
break;
//...
}
//or if condition
if(listItem.getText().toString().equals(values[0]) {
Intent myintent0 = new Intent(view.getContext(), Main2Activity.class);
startActivityForResult(myintent0, 0);
}
}