Как вытащить строки из массива, адаптированного списка для кликаемого элемента списка - PullRequest
1 голос
/ 04 августа 2010

хорошо, поэтому у меня есть список, адаптированный к массиву (адаптация массива выполняется в другом классе). Я только что получил прослушиватель кликов, работающий для списка, но теперь я хочу настроить его так, чтобы при нажатии на элемент он вытягивал строки из элемента, по которому щелкнули мышью, и связать их с намерением нового действия. Я полагаю, что я должен использовать intent.putextra, однако я не уверен, как получить правильные строки, соответствующие элементу, на который я нажимаю ... мой код ниже .. я просто потерян, чтобы быть честным

//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+ "$";
}

}

и добавить мой класс оповещений.

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;
}

}

Ответы [ 2 ]

0 голосов
/ 09 августа 2010
В выходные дни

прозвучало прозрение о том, как решить эту проблему, и я, наконец, нашел хорошую работу для своего приложения. Я знаю, что это не оптимально, потому что я жестко закодировал число 100 в нем, но для моих целей на данный момент я знаю, что у меня никогда не будет столько пунктов списка ..

я добавил эти 2 бита кода в мой класс оповещения об адаптере

int startzero = 0;

public static String[][] promomatrix = new String[6][100];

и

promomatrix [0] [startzero] = al.cityid; промоматрикс [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++;

затем пошел в мой класс homepageactivity и добавил это в прослушиватель кликов

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);

и, наконец, перешел к моей рекламной деятельности (где я пытался отправить строки) и добавил это

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");

работал как шарм .. надеюсь, это кому-нибудь поможет:)

0 голосов
/ 04 августа 2010

Вам необходимо использовать параметры события onItemClick.

. Полный более читаемый список параметров с именем параметра равен

(AdapterView<?> parent, View view, int pos, long id)

, что означает, что у вас есть параметр pos, который указывает положение вадаптер.

Что вам нужно сделать, это:

  • перейти к pos в адаптере
  • считывать значения с адаптера
  • использовать putExtra, чтобы подписаться на намерение
...