ok, поэтому у меня есть адаптированное к массиву listview (адаптация массива выполняется в другом классе). Я просто получил прослушиватель кликов, работающий над этим списком, но теперь я хочу настроить его, чтобы при щелчке элемента строки из щелкнутого элемента и копирует их на намерение к новой активности. Я полагаю, что я предполагаю использовать намерение .putextra, однако я не уверен, как вытащить правильные строки, соответствующие элементу, на который я нажимаю.. мой код ниже.. im просто потерял, чтобы быть честным
//Initialize the ListView
lstTest = (ListView)findViewById(R.id.lstText);
//Initialize the ArrayList
alrts = new ArrayList<Alerts>();
//Initialize the array adapter notice with the listitems.xml layout
arrayAdapter = new AlertsAdapter(this, R.layout.listitems,alrts);
//Set the above adapter as the adapter for the list
lstTest.setAdapter(arrayAdapter);
//Set the click listener for the list
lstTest.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView adapterView, View view, int item, long arg3) {
Intent intent = new Intent(
HomePageActivity.this,
PromotionActivity.class
);
finish();
startActivity(intent);
}
});
мой класс предупреждений.
public class Alerts {
public String cityid;
public String promoterid;
public String promoshortcontent;
public String promocontent;
public String promotitle;
public String locationid;
public String cover;
@Override
public String toString() {
return "City: " +cityid+ " Promoter: " +promoterid+ "Short Promotion: " +promoshortcontent+ "Promotion: " +promocontent+ "Title: " +promotitle+ "Location: " +locationid+ "Cover: " +cover+ "$";
}
}
иdddd мой класс alertadapter..
public class AlertsAdapter extends ArrayAdapter<Alerts> {
int resource;
String response;
Context context;
//Initialize adapter
public AlertsAdapter(Context context, int resource, List<Alerts> items) {
super(context, resource, items);
this.resource=resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
LinearLayout alertView;
//Get the current alert object
Alerts al = getItem(position);
//Inflate the view
if(convertView==null)
{
alertView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, alertView, true);
}
else
{
alertView = (LinearLayout) convertView;
}
//Get the text boxes from the listitem.xml file
TextView textPromo =(TextView)alertView.findViewById(R.id.txtPromo);
TextView textPromoter =(TextView)alertView.findViewById(R.id.txtPromoter);
TextView textLocation =(TextView)alertView.findViewById(R.id.txtLocation);
//Assign the appropriate data from our alert object above
textPromo.setText(al.promocontent);
textPromoter.setText(al.promoterid);
textLocation.setText(al.locationid);
return alertView;
}
}
имел прозрение в течение выходных о том, как исправить эту проблему, и я наконец нашел хорошую работу для своего приложения. Я знаю, что это не оптимально, потому что я жестко закодировал номер 100, но для моего использования на данный момент я знаю, что у меня никогда не будет такого количества элементов списка.
Я добавил эти 2 бита кода в мой класс alertadapter
int startzero = 0;
public static String[][] promomatrix = new String[6][100];
и
promomatrix [0] [startzero] = al.cityid; promomatrix [1] [startzero] = al.promoterid; promomatrix [2] [startzero] = al.promocontent; promomatrix [3] [startzero] = al.promotitle; promomatrix [4] [startzero] = al.locationid; promomatrix [5] [startzero] = al.cover;
startzero++;
затем перешел на мой начальный класс активности и добавил его в список прослушивателей
Intent intent = new Intent(
HomePageActivity.this,PromotionActivity.class);
intent.putExtra("listitemcity", AlertsAdapter.promomatrix[0][pos]);
intent.putExtra("listitempromoter", AlertsAdapter.promomatrix[1][pos]);
intent.putExtra("listitemcontent", AlertsAdapter.promomatrix[2][pos]);
intent.putExtra("listitemtitle", AlertsAdapter.promomatrix[3][pos]);
intent.putExtra("listitemlocation", AlertsAdapter.promomatrix[4][pos]);
intent.putExtra("listitemcover", AlertsAdapter.promomatrix[5][pos]);
finish();
startActivity(intent);
и, наконец, перешел на мою promotionactivity (где я пытался отправить строки) и добавил это
Bundle extras = getIntent().getExtras();
if (extras == null){
return;
}
String listitemcity = extras.getString("listitemcity");
String listitempromoter = extras.getString("listitempromoter");
String listitemcontent = extras.getString("listitemcontent");
String listitemtitle = extras.getString("listitemtitle");
String listitemlocation = extras.getString("listitemlocation");
String listitemcover = extras.getString("listitemcover");
работал как шарм. Надеюсь, это поможет кому-то:)
Вам нужно использовать параметры события onItemClick
более читаемый параметр enum с именем param
(AdapterView<?> parent, View view, int pos, long id)
означает, что у вас есть параметр pos
, указывающий положение в адаптере.
Что вам нужно сделать:
pos
в адаптере
getItem
который вы можете использовать для получения элемента в pos. Это, вероятно, строка, так что вы закончили и с шагом 2. Это будет что-то вроде:String myItem = HomePageActivity.this.arrayAdapter.getItem(item)