2016-03-01 4 views
1

Итак, я создал собственный ListView с двумя объектами в списке. Например, первым в списке является Cats, а второй - Dogs. Затем, когда один нажат, он перейдет к другому экрану активности. Например, когда пользователь нажимает «Собаки», он перейдет на другой экран с новым списком с именами в списке, такими как «Corgi», «Pug», «Husky» и т. Д. Затем, когда породы собак нажмите, он перейдет на веб-сайт. Например, когда пользователь нажимает «Corgi», он пересылает пользователя на страницу Wiki Corgi.Android - Пользовательский ListView, связанный с веб-сайтом

Как я могу создать третью часть приложения?

Мой код выглядит следующим образом:

MainActivity:

public class MainActivity extends ListActivity implements OnItemClickListener { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     String[] data = { "Dogs", "Cats" }; 
     int[] icons = { R.drawable.dogz, R.drawable.catz }; 

     // Provide the cursor for the list view. 
     setListAdapter(new CustomListAdapter(this, data, icons)); 

     /* setOnItemClickListener() Register a callback to be invoked when an item 
     * in this AdapterView has been clicked. 
     */ 
     getListView().setOnItemClickListener(this); 

    } 

    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, 
      long id) { 
     Intent intent = new Intent(parent.getContext(), ChildActivity.class); 

     // Add extended data to the intent. 
     intent.putExtra("POSITION", position); 

     /* 
     * Launch a new activity. You will not receive any information about when 
     * the activity exits. This implementation overrides the base version, 
     * providing information about the activity performing the launch. 
     */ 
     startActivity(intent); 
    } 

} 

ChildActivity:

public class ChildActivity extends ListActivity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     String[][] data = { 
       { "Corgi", "Pugs", "Husky" }, 
       { "Siamese", "Persian", "Maine Coon" } }; 
     int[][] icons = { 
       { R.drawable.d, R.drawable.e, R.drawable.f }, 
       { R.drawable.a, R.drawable.b, R.drawable.c }, }; 
     Intent intent = getIntent(); 
     int position = intent.getIntExtra("POSITION", 0); 

     // Provide the cursor for the list view. 
     setListAdapter(new CustomListAdapter(this, data[position], 
       icons[position])); 

    } 

} 

CustomListAdapter:

public class CustomListAdapter extends ArrayAdapter<String> { 

    private final Context context; 
    private final String[] values; 
    private final int[] icons; 

    public CustomListAdapter(Context context, String[] values, int[] icons) { 
     super(context, R.layout.row_layout, values); 
     this.context = context; 
     this.values = values; 
     this.icons = icons; 
    } 

    @Override 
    // Get a View that displays the data at the specified position in the data set. 
    public View getView(int position, View convertView, ViewGroup parent) { 

     /* 
     * Instantiates a layout XML file into its corresponding View objects. 
     * It is never used directly. Instead, use getSystemService(String) to 
     * retrieve a standard LayoutInflater instance that is already hooked up to 
     * the current context and correctly configured for the device you are running on. 
     */ 
     LayoutInflater inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     /* 
     * Inflate a new view hierarchy from the specified xml resource. 
     * Throws InflateException if there is an error. 
     */ 
     View rowView = inflater.inflate(R.layout.row_layout, parent, false); 
     TextView textView = (TextView) rowView.findViewById(R.id.txtStatus); 
     textView.setText(values[position]); 
     Drawable draw = context.getResources().getDrawable(icons[position]); 
     Bitmap bitmap = ((BitmapDrawable) draw).getBitmap(); 
     int h = bitmap.getHeight(); 
     int w = bitmap.getWidth(); 
     Drawable newDraw = new BitmapDrawable(context.getResources(), 
       Bitmap.createScaledBitmap(bitmap, 40 * w/h, 40, true)); 

     /* 
     * Sets the Drawables (if any) to appear to the left of, above, to the right of, 
     * and below the text. Use 0 if you do not want a Drawable there. 
     * The Drawables' bounds will be set to their intrinsic bounds. 
     */ 
     textView.setCompoundDrawablesWithIntrinsicBounds(newDraw, null, null, 
       null); 
     return rowView; 
    } 
} 

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

+0

Я бы не добавил новую деятельность - посмотрите на намерение: http://stackoverflow.com/questions/2201917/how-can-i-open-a-url-in-androids-web- browser-from-my-application – russianmario

+0

@ russianmario Если я игнорирую третье действие и добавляю код «browserIntent». Как я буду использовать каждый URL для каждой породы? – Wooster

+0

Вместо того, чтобы создавать массив строк для отображения каждой породы, вы, вероятно, захотите создать породу класса, которая содержит имя породы и URL-адрес, к которому вы хотите перейти, а затем создать список . Вы можете продолжать использовать ArrayAdapter (с некоторыми изменениями для использования объекта Breed). Затем используйте событие 'onItemClick': http://stackoverflow.com/a/16746579/3163097 – russianmario

ответ

0

Что вы подразумеваете под третьей частью приложения? Открытие веб-сайта при нажатии на породу собаки?

+0

Да. Так что скажем: «Собака» -> «Корги» -> Страница Wiki. – Wooster

0
  1. Попробуйте сделать адаптер с Animal.
  2. OnItemClick() открыть WebViewFragment и передать его либо ваш Animal объекта или Animal.getUrl() -String в Bundle
  3. (опции) Проверьте ExpandableListView, чтобы предотвратить ненужные глубокие иерархии навигации.