很久以後,我回到Android,我有點卡住了一些問題。
該應用程序由佈局列表組成,每個佈局都通過適配器由模型支持。
每個佈局有幾個視圖,其中之一是一個微調。
我想在更改微調器的值時修改適配器中的數據,但我不知道如何引用適配器中的對象。如何從ListView中的視圖訪問適配器對象
public class MainActivity extends AppCompatActivity {
ArrayList<Troop> values = new ArrayList<Troop>();
MySimpleArrayAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
values.add(new Troop());
final ListView listView =(ListView) findViewById(R.id.listview);
adapter = new MySimpleArrayAdapter(
this,
values);
listView.setAdapter(adapter);
}
public class Troop {
private String weapon;
private int bs;
private int total_modifier;
public Troop() {
}
public int getBs() {
return bs;
}
public void setBs(int bs) {
this.bs = bs;
}
}
public class MySimpleArrayAdapter extends ArrayAdapter {
private final Context context;
private ArrayList<Troop> troopers;
private String[] possible_bs = new String[] {"10", "11", "12", "13", "15", "16"};
public MySimpleArrayAdapter(Context context, ArrayList<Troop> values) {
super(context, -1, values);
this.context = context;
this.troopers = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
Spinner bs_spinner = rowView.findViewById(R.id.bs_spinner);
ArrayAdapter<String> bs_adapter = new ArrayAdapter<String>(
context,
android.R.layout.simple_spinner_dropdown_item,
possible_bs);
bs_spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
bs_spinner.setAdapter(bs_adapter);
return rowView;
}
}
public class CustomOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
// I want to call getBs on the Trooper correspoding to this view here
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}
你應該'擴展ArrayAdapter' –
謝謝您的回答。問題是,如何從onItemSelected方法訪問適配器? –
這是一個評論,而不是答案;)哪個適配器? –