2014-01-16 4 views
0

У меня есть вид деятельности countryActivity и класс модели с именем Страна. Я хочу установить значения в классе модели и сохранить каждый объект в arraylist, а также показать значения объектов в gridview. Когда элементы будут нажаты, я хочу получить объекты. Ниже приведены мои коды. Где я ошибся или что делать? помогите мне плз?Как получить объект из GridView itemClick

activity_country.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=".CountryActivity" > 


<TextView 
    android:id="@+id/nTextView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentTop="true" 
    android:layout_marginLeft="21dp" 
    android:layout_marginTop="26dp" 
    android:text="Name" /> 

<TextView 
    android:id="@+id/aTextView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/nTextView" 
    android:layout_below="@+id/nTextView" 
    android:layout_marginTop="24dp" 
    android:text="About" /> 

<EditText 
    android:id="@+id/CountryNameEditText" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignBaseline="@+id/nTextView" 
    android:layout_alignBottom="@+id/nTextView" 
    android:layout_marginLeft="48dp" 
    android:layout_toRightOf="@+id/nTextView" 
    android:ems="10" > 

    <requestFocus /> 
</EditText> 

<EditText 
    android:id="@+id/CountryAboutEditText" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/CountryNameEditText" 
    android:layout_alignTop="@+id/aTextView" 
    android:ems="10" /> 

<Button 
    android:id="@+id/saveCountryButton" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/CountryAboutEditText" 
    android:layout_below="@+id/CountryAboutEditText" 
    android:layout_marginLeft="16dp" 
    android:layout_marginTop="22dp" 
    android:text="Save" 
    android:onClick="saveCountry" 
    /> 

<GridView 
    android:id="@+id/countryGridView" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/saveCountryButton" 
    android:layout_centerHorizontal="true" 
    android:numColumns="2"> 
</GridView> 
</RelativeLayout> 

CountryActivity.java

public class CountryActivity extends Activity 
{ 
ArrayList<Country> countries = new ArrayList<Country>(); 
Country aCountry; 

EditText CountryNameTxtBox; 
EditText CountryAboutTxtBox; 
GridView countrygGridView; 

@Override 
protected void onCreate(Bundle savedInstanceState) 
    { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_country); 
    // Show the Up button in the action bar. 

    CountryNameTxtBox = (EditText)findViewById(R.id.CountryNameEditText); 
    CountryAboutTxtBox = (EditText)findViewById(R.id.CountryAboutEditText); 
    countrygGridView = (GridView)findViewById(R.id.countryGridView); 

} 
if((txtName!="" || txtName!=null) && (txtAbout!="" || txtAbout != null)) 
    { 
     aCountry = new Country(txtName, txtAbout); 
     countries.add(aCountry); 
    } 

    showGrid(); 

} 


public void showGrid() 
{ 
    ArrayList<Country> list2 = new ArrayList<Country>(); 

    for(Country arrCountry : countries) 
    { 
      list2.add(aCountry); 

    } 


     ArrayAdapter<Country> adapter2 = new ArrayAdapter<Country>(this,android.R.layout.simple_list_item_1, list2); 
     countrygGridView.setAdapter(adapter2); 


countrygGridView.setOnItemClickListener(new OnItemClickListener() 
    { 
@Override 
public void onItemClick(AdapterView<?> parent, View v,int position, long id) 
    { 
    aCountry = (Country) v.getTag(); 
     for(Country mCountry: countries) 
     { 
     if(countries.contains(aCountry)) 
     { 
     Toast.makeText(CountryActivity.this, "match", 2000).show(); 
     } 
      } 
     } 
    }); 
    } 
} 

Country.java (класс модель)

public class Country 
{ 

private String name; 
private String about; 
    ArrayList<City> cities; 

public Country() 
{ 
    cities = new ArrayList<City>(); 
} 

    public Country(String name, String about) 
{ 
    this.name= name; 
    this.about = about; 
} 


public int getNoOfCities() 
{ 
    return cities.size(); 
} 


public long getNoOfCitizens() 
{ 
     Long aPop= 0L; 
    for(City aCity: cities) 
    { 
      aPop += aCity.getPopulation(); 
    } 
    return aPop; 
} 



public String getName(){ 
    return name; 

} 
public String getAbout(){ 
    return about; 

} 
} 
+0

Думаю, что это будет решить: http://stackoverflow.com/questions/21164478/customadapter-for-object-isnt-working –

ответ

1

В методе onItemClick просто сделайте list2.get(position), и у вас есть ваша страна.

+0

Но я добавлять объект в ArrayList и адаптера, так и в girdview его отображение самого объекта. Я хочу показать значения в gridview (имя и примерно из класса Country.java). и снова, когда listItems в gridview щелкнул, я хочу получить объект, чтобы я мог класс модели получить значения из объекта. –

+0

Затем вам нужно создать собственный адаптер, который делает это. Простой ArrayAdapter не может знать, что вы хотите отобразить. – FWeigl

+0

Я сделал это правильно? Http: // StackOverflow.com/questions/21164478/customadapter-for-object-isnt-working :-) –

0

Фикс на код

 countrygGridView.setOnItemClickListener(new OnItemClickListener() 
     { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View v,int position, long id) 
     { 
       Country cnt = (Country)countrygGridView.getAdapter().getItem(position); 
     }); 
     } 
0

В onItemClick для GridView вы получите позицию элемента, который вы нажали

Country country = countries.get(position); 

Refer this

0

(В методе onItemClick, просто положил:

Country aCountry = countries.get(position); 

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

Вы должны сравнивать строки с помощью «равно», а не «==», используйте & & вместо ||, потому что я полагаю, вы хотите, чтобы все условия, происходят одновременно и проверить нуль перед проверкой фактического значения вашей строки , так что заменить:

if((txtName!="" || txtName!=null) && (txtAbout!="" || txtAbout != null)) 

с:

if(txtName!=null && !txtName.equals("") && txtAbout != null && !txtAbout.equals("")) 
0

Если вы хотите дисплеи имени и о использовании ArrayAdapter, вы должны переопределить метод toString в классе Country.

String toString() { 
    return this.name + " " + this.about; 
} 
Смежные вопросы