2014-12-19 1 views
0

я есть фрагмент с ListViewЗагрузите строку spesific из списка щелкнутого списка?

myfragment:

public class LightFragment extends Fragment { 
String[] name; 
String[] type; 
String[] swim; 
int[] flag; 
ListView list; 
ListViewAdapter adapter; 

public LightFragment(){} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    View rootView = inflater.inflate(R.layout.fragment_light, container, false); 

    name = getResources().getStringArray(R.array.sport); 

    type = new String[] { "China", "India", "United States", 
      "Indonesia", "Brazil" }; 

    swim = new String[] { "1,354,040,000", "1,210,193,422", 
      "315,761,000", "237,641,326", "193,946,886" }; 

    flag = new int[] { R.drawable.light11, 
      R.drawable.light12,    
      R.drawable.light21, 
      R.drawable.light22, 
      R.drawable.light23, 
      R.drawable.light24, 
      R.drawable.light25, 
      R.drawable.light26, 
      R.drawable.light27 }; 

    // Locate the ListView in fragmenttab1.xml 
    list = (ListView) rootView.findViewById(R.id.listview); 

    // Pass results to ListViewAdapter Class 
    adapter = new ListViewAdapter(getActivity(), name, type, swim, 
      flag); 
    // Binds the Adapter to the ListView 
    list.setAdapter(adapter); 
    // Capture clicks on ListView items 
    list.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, 
       int position, long id) { 
      // Send single item click data to SingleItemView Class 
      Intent i = new Intent(getActivity(), SingleItemView.class); 
      // Pass all data rank 
      i.putExtra("rank", name); 
      // Pass all data country 
      i.putExtra("country", type); 
      // Pass all data population 
      i.putExtra("population", swim); 
      // Pass all data flag 
      i.putExtra("flag", flag); 
      // Pass a single position 
      i.putExtra("position", position); 
      // Open SingleItemView.java Activity 
      startActivity(i); 
     } 

    }); 

    return rootView; 
} 

}

Listviewadapter:

public class ListViewAdapter extends BaseAdapter { 

// Declare Variables 
Context context; 
String[] rank; 
String[] country; 
String[] population; 
int[] flag; 
LayoutInflater inflater; 

public ListViewAdapter(Context context, String[] rank, String[] country, 
     String[] population, int[] flag) { 
    this.context = context; 
    this.rank = rank; 
    this.country = country; 
    this.population = population; 
    this.flag = flag; 
} 

public int getCount() { 
    return rank.length; 
} 

public Object getItem(int position) { 
    return null; 
} 

public long getItemId(int position) { 
    return 0; 
} 

public View getView(int position, View convertView, ViewGroup parent) { 

    // Declare Variables 
    TextView txtrank; 
    TextView txtcountry; 
    TextView txtpopulation; 
    ImageView imgflag; 

    inflater = (LayoutInflater) context 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    View itemView = inflater.inflate(R.layout.listview_item, parent, false); 

    // Locate the TextViews in listview_item.xml 
    txtrank = (TextView) itemView.findViewById(R.id.name); 
    txtcountry = (TextView) itemView.findViewById(R.id.type); 
    txtpopulation = (TextView) itemView.findViewById(R.id.swim); 
    // Locate the ImageView in listview_item.xml 
    imgflag = (ImageView) itemView.findViewById(R.id.flag); 

    // Capture position and set to the TextViews 
    txtrank.setText(rank[position]); 
    txtcountry.setText(country[position]); 
    txtpopulation.setText(population[position]); 

    // Capture position and set to the ImageView 
    imgflag.setImageResource(flag[position]); 

    return itemView; 
} 

}

mysingleviewitem:

public class SingleItemView extends Activity { 

TextView txtname; 
TextView txttype; 
TextView txtswim; 
TextView txtfunny; 
TextView txtwalking; 
TextView txtangry; 
TextView txtsad; 
ImageView imgflag; 
String[] name; 
String[] type; 
String[] swim; 
String[] funny; 
String[] walking; 
String[] angry; 
String[] sad; 
int[] flag; 
int position; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.singleitemview); 

    Intent i = getIntent(); 
    // Get a single position 
    position = i.getExtras().getInt("position"); 
    // Get the list of rank 
    name = i.getStringArrayExtra("rank"); 
    // Get the list of country 
    type = i.getStringArrayExtra("country"); 
    // Get the list of population 
    swim = i.getStringArrayExtra("population"); 

    funny = i.getStringArrayExtra("rank"); 
    // Get the list of country 
    walking = i.getStringArrayExtra("country"); 
    // Get the list of population 
    angry = i.getStringArrayExtra("population"); 

    sad = i.getStringArrayExtra("rank"); 
    // Get the list of flag 
    flag = i.getIntArrayExtra("flag"); 

    // Locate the TextViews in singleitemview.xml 
    txtname = (TextView) findViewById(R.id.name); 
    txttype = (TextView) findViewById(R.id.type); 
    txtswim = (TextView) findViewById(R.id.swim); 
    txtfunny = (TextView) findViewById(R.id.funny); 
    txtwalking = (TextView) findViewById(R.id.walking); 
    txtangry = (TextView) findViewById(R.id.angry); 
    txtsad = (TextView) findViewById(R.id.sad); 

    // Locate the ImageView in singleitemview.xml 
    imgflag = (ImageView) findViewById(R.id.flag); 

    // Load the text into the TextViews followed by the position 
    txtname.setText(name[position]); 
    txttype.setText(type[position]); 
    txtswim.setText(swim[position]); 
    txtfunny.setText(funny[position]); 
    txtwalking.setText(walking[position]); 
    txtangry.setText(angry[position]); 
    txtsad.setText(sad[position]); 

    // Load the image into the ImageView followed by the position 
    imgflag.setImageResource(flag[position]); 
} 

}

MyArray:

<string-array name="sport"> 
    <item >Lari</item> 
    <item >Bola</item> 
    <item >Balap</item> 
    <item >tinju</item> 
    <item >renang</item> 
</string-array> 


<string-array name="Lari"> 
    <item >100 meter</item> 
    <item >mulai</item> 
    <item >finish</item> 
    <item >piala</item> 
</string-array> 

деталь: ListViewItem с названием строки массива "спорт" и управляется в соответствии с компоновкой строка массива.

и при нажатии откроется singleviewitem ListView, но я хочу, чтобы слова, которые появляются взяты из <string-array name = "Lari"> и так далее по ListView из <string-array name = "sport">

так, например, я нажимаю ListView с КОЛОНТИТУЛОМ будет вне есть

<item >100 meter</item> 
<item >mulai</item> 
<item >finish</item> 
<item >piala</item> 

Пожалуйста, помогите,

жаль, мой английский плохо

пь: Я т ried getstringarray позиция, но только поднимает строку в соответствии с положением щелкнутого списка.

+0

возможно дубликат [? Как получить объект из ListView в setOnItemClickListener в андроиде] (http://stackoverflow.com/ Вопросы/7073577/how-to-get-object-from-listview-in-setonitemclicklistener-in-android) –

ответ

0

Из-за репутации я не могу оставить комментарий, но вы можете просто получить текст из выбранного массива и сравнить его с любым именем. Если я правильно понял, ваша проблема заключается в том, что вы не можете загрузить массив из res/массивов с тем же именем, которое нажал элемент в listview.

Я решил его, выполнив поиск по массиву, щелкнув слово, и если совпадал - взял его. Все действия здесь внутри onItemClickListener Например:

String[] myString = null; 
String text = parent.getItemAtPosition(position).toString(); 

if(text.equalsIgnoreCase("Lari")){ 
    myString = getResources().getStringArray(R.array.lari); 
}else if(text.equalsIgnoreCase("sport")){ 
    myString = getResources().getStringArray(R.array.sport); 
} 

И тогда вы можете пройти этот массив через намерение и заполнить ваш следующий listview. Надеюсь, это то, что вы хотите.

EDIT: Когда вы получили имя щелкнутого списка, вы можете найти тот же массив в res/array. После этого просто передайте этот массив через Intent и заполните следующий список этим массивом, используя Adapter.

Intent intent = new Intent(this, YourNextActivity.class); 
intent.putExtra("justNameForArray", mString); 

В следующем упражнении вы можете получить этот массив:

Intent intent = getIntent(); 
String[] arrayFromPreviousClass = intent.getStringArrayExtra("justNameForArray"); 

И после этого вы можете заполнить новый список.

Если вы говорите, что вы хотите третий ListItem, вы можете поймать его в onItemClickListener:

switch(position){ 
     case 0: 
      //do smthg; 
     break; 
     case 1: 
      //do smthg; 
     break; 
     case 2: 
     //here you may get your string array and pass it through intent to another activity with another view 
     break; 
    } 
+0

thx для ответа, что я хочу, в настоящее время нажата третье listview, он появится singleview со словами/строками string- массив на основе строки в последней трети (строка в listview, взятая из массива строк, я сделал только шоу-заголовки только в lightfragment), во всяком случае, что такое репутация? извините новичок – janobyl

+0

@janobyl, я отредактировал ответ, взгляните) – Yurets

+0

Можете ли вы объяснить, в каком классе я поставил код? и полный код, я запутался – janobyl