2013-10-15 4 views
0

У меня есть этот проект, чтобы просто получить данные gridview в listview, но im kinda new для затмения, поэтому я так запутался, как это сделать , Вот строка кодов у меня есть на данный моментКак получить данные из gridview в listview с помощью onclicklistener

package com.smartcartv2; 

import java.util.ArrayList; 
import java.util.List; 

import android.annotation.TargetApi; 
import android.app.Activity; 
import android.content.Intent; 
import android.os.Build; 
import android.os.Bundle; 
import android.support.v4.app.NavUtils; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.GridView; 
import android.widget.ImageView; 
import android.widget.TextView; 
import android.widget.Toast; 

public class DisplayCondiments extends Activity { 
    private List<Condiments> myCondiments= new ArrayList<Condiments>(); 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_display_condiments); 
     // Show the Up button in the action bar. 
     setupActionBar(); 
     populateCondimentList(); 
     populateGridview(); 
     callBack(); 
    } 

    private void populateCondimentList() { 
     //This codes adds the items to the listview according each lines 
     //myCondiments.add(new Condiments(R.drawable.ic_launcher, "Android", "100")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 
     myCondiments.add(new Condiments(R.drawable.download, "Mang Tomas", "50")); 


    } 
    private void populateGridview() { 
     ArrayAdapter<Condiments> adapter =new MyListAdapter(); 
     GridView list = (GridView) findViewById(R.id.CondimentsGridview); 
     list.setAdapter(adapter); 

    } 

    private void callBack(){ 
     GridView list=(GridView) findViewById(R.id.CondimentsGridview); 
     list.setOnItemClickListener(new AdapterView.OnItemClickListener(){ 

      @Override 
      public void onItemClick(AdapterView<?> parent, View viewClicked, int position, 
        long id) { 

       Condiments clickedProduct =myCondiments.get(position); 
       String message ="You clicked " + clickedProduct.getProduct() 
           +"which costs " + clickedProduct.getPrice(); 
       Toast.makeText(DisplayCondiments.this, message, Toast.LENGTH_LONG).show(); 

      } 

     }); 
    } 

    private class MyListAdapter extends ArrayAdapter<Condiments>{ 
     public MyListAdapter(){ 
      super(DisplayCondiments.this, R.layout.item_layout, myCondiments); 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      View itemView=convertView; 
      if (itemView==null){ 
       itemView=getLayoutInflater().inflate(R.layout.item_layout, parent, false); 
      } 
      //This Line of codes populates the gridview 
      Condiments currentCondiment=myCondiments.get(position); 
      ImageView imageView =(ImageView)itemView.findViewById(R.id.icon_id); 
      imageView.setImageResource(currentCondiment.getIconID()); 

      TextView ProductText=(TextView)itemView.findViewById(R.id.txtName); 
      ProductText.setText(currentCondiment.getProduct()); 

      TextView PriceText=(TextView)itemView.findViewById(R.id.txtPrice); 
      PriceText.setText(currentCondiment.getPrice()); 

      return itemView; 
     } 


    } 

    /** 
    * Set up the {@link android.app.ActionBar}, if the API is available. 
    */ 
    @TargetApi(Build.VERSION_CODES.HONEYCOMB) 
    private void setupActionBar() { 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
      getActionBar().setDisplayHomeAsUpEnabled(true); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.display_condiments, menu); 
     return true; 
    } 


    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
     case android.R.id.home: 
      // This ID represents the Home or Up button. In the case of this 
      // activity, the Up button is shown. Use NavUtils to allow users 
      // to navigate up one level in the application structure. For 
      // more details, see the Navigation pattern on Android Design: 
      // 
      // http://developer.android.com/design/patterns/navigation.html#up-vs-back 
      // 
      NavUtils.navigateUpFromSameTask(this); 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

} 

и вот мой XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".DisplayCondiments" > 

    <GridView 
     android:id="@+id/CondimentsGridview" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentTop="true" 
     android:layout_marginLeft="164dp" 
     android:numColumns="3" 
     tools:listitem="@android:layout/simple_list_item_2" > 

    </GridView> 

    <ListView 
     android:id="@+id/listView1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignRight="@+id/CondimentsGridview" 
     android:layout_alignTop="@+id/CondimentsGridview" 
     android:layout_marginRight="829dp" > 

    </ListView> 

</RelativeLayout> 

мне действительно нужна помощь здесь :(извините за нуб в этом

+0

Что значит «получить данные gridview в listview»? – FoamyGuy

+0

Я имею в виду получение данных из gridview, а затем отображение его в listview – HelloWorld

+0

Если вы хотите, чтобы все те же данные в ListView, что и в GridView, просто устанавливали ListView в тот же адаптер, который хранит все ваши данные ... Что в частности, у вас проблемы? – FoamyGuy

ответ

1

От чтения вы комментируете, я думаю, что знаю, что вы пытаетесь сделать. Лучше всего в вашем адаптере gridview, когда вы заполняете каждое представление, добавляете тег. view.addTag(); Здесь вы можете добавить объект в качестве тега Этот крик объекта содержит все данные, которые вы хотите в своем lis t. Удостоверьтесь, что объект объект реализует Parcelable. Это помогает при прохождении объектов. Вы можете думать о нем как о сериализации (вроде).

Когда вы реализуете свой onclick для gridview, просто получите тег, переведите его обратно в oject, если хотите, или передайте его как есть (parcelable), а затем заполните данные в своем списке, используя другой настраиваемый адаптер, предназначенный для ListView

list.setOnItemClickListener (новый AdapterView.OnItemClickListener() {

 @Override 
     public void onItemClick(AdapterView<?> parent, View viewClicked, int position, 
       long id) { 
     YourOBJ obj = (YourObj)viewClicked.getTag(); 
     //pass it to the listview addapter 
     } 

    }); 
} 

Просмотр тега http://developer.android.com/reference/android/nfc/Tag.html

андроида Parcelable http://developer.android.com/reference/android/os/Parcelable.html

Смежные вопросы