2015-12-18 3 views
-1

Я запрограммировал ListView на моем MainActivity с видом на изделие и классом автомобиля.Как я могу добавлять элементы из списка с помощью кнопки в другой список в другой деятельности?

public class Car { 
    private String make; 
    private int year; 
    private int iconID; 
    private String condition; 

    public Car(String make, int year, int iconID, String condition) { 
     this.make = make; 
     this.year = year; 
     this.iconID = iconID; 
     this.condition = condition; 
    } 

    public String getMake() {return make;} 

    public int getYear() {return year;} 

    public int getIconID() {return iconID;} 

    public String getCondition() {return condition;} 


} 

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

public class MainActivity extends AppCompatActivity { 

    Toolbar toolbar; 
    ActionBar actionBar; 

    private List<Car> myCars = new ArrayList<Car>(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     MyListAdapter adapter = new MyListAdapter(); 

     toolbar = (Toolbar) findViewById(R.id.toolbar1); 
     setSupportActionBar(toolbar); 

     actionBar = getSupportActionBar(); 

     populateCarList(); 
     populateListView(); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show(); 
      } 
     }); 
    } 

    private void populateCarList() { 
     myCars.add(new Car("Ford", 1940, R.mipmap.ic_launcher, "Needing work")); 
     myCars.add(new Car("Benz", 1960, R.mipmap.ic_launcher, "Cheap")); 
     myCars.add(new Car("Mustang", 2000, R.mipmap.ic_launcher, "Needing new owner")); 
     myCars.add(new Car("BMW", 2012, R.mipmap.ic_launcher, "Needing a lot of work!")); 
     myCars.add(new Car("Toyota", 1940, R.mipmap.ic_launcher, "Oldtimer")); 
     myCars.add(new Car("VW", 2003, R.mipmap.ic_launcher, "Cool")); 
     myCars.add(new Car("Ferrari", 2008, R.mipmap.ic_launcher, "Nice")); 

    } 

    private void populateListView() { 
     ArrayAdapter<Car> adapter = new MyListAdapter(); 
     ListView list = (ListView) findViewById(R.id.carsListView); 

     TextView textView = new TextView(MainActivity.this); 
     textView.setText("Here you can see all the Cars!"); 
     textView.setTextSize(15); 
     textView.setGravity(Gravity.CENTER_HORIZONTAL); 
     textView.setTypeface(null, Typeface.BOLD); 
     textView.setTextColor(Color.parseColor("#a60b0b")); 
     list.addHeaderView(textView); 

     list.setAdapter(adapter); 

    } 

    private class MyListAdapter extends ArrayAdapter<Car> { 
     public MyListAdapter() { 
      super(MainActivity.this, R.layout.item_view, myCars); 
     } 

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

      View itemView = convertView; 
      if(itemView == null){ 
       itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false); 
      } 

      String url; 
      switch(position){ 
       case 0: url = "http://www.google.com"; break; 
       case 1: url = "http://www.google.com"; break; 
       case 2: url = "http://www.google.com"; break; 
       case 3: url = "http://www.google.com"; break; 
       case 4: url = "http://www.google.com"; break; 
       case 5: url = "http://www.google.com"; break; 
       case 6: url = "http://www.google.com"; break; 
       default: url = "http://www.google.com"; break; 
      } 
      Button button = (Button)itemView.findViewById(R.id.item_button); 
      button.setTag(url); 
      button.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        String url = (String)v.getTag(); 

        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); 
       } 
      }); 

      Car currentCar = myCars.get(position); 


      ImageView imageView = (ImageView) itemView.findViewById(R.id.item_icon); 
      imageView.setImageResource(currentCar.getIconID()); 

      // Make: 
      TextView makeText = (TextView) itemView.findViewById(R.id.item_txtMake); 
      makeText.setText(currentCar.getMake()); 

      // Year: 
      TextView yearText = (TextView) itemView.findViewById(R.id.item_txtYear); 
      yearText.setText("" + currentCar.getYear()); 

      // Condition: 
      TextView conditionText = (TextView) itemView.findViewById(R.id.item_txtCondition); 
      conditionText.setText(currentCar.getCondition()); 


      return itemView; 
     } 
    } 

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

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     if (id == android.R.id.home){ 
      onBackPressed(); 
      return true; 
     } 

     if (id == R.id.watchList) { 
      startActivity(new Intent(this, WatchListActivity.class)); 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    public void addCarToWatchList (View view){ 
     Toast.makeText(MainActivity.this, "Car has been added to WatchList", Toast.LENGTH_SHORT).show(); 
    } 
} 

И у меня также есть WatchList класс (или FavoriteCarsList класса, что вы хотите назвать его)

public class WatchListActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_watch_list); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 



     getSupportActionBar().setHomeButtonEnabled(true); 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 


     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show(); 
      } 
     }); 
    } 



    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     if (id == android.R.id.home){ 
      onBackPressed(); 
      return true; 
     } 

     if (id == R.id.watchList) { 
      startActivity(new Intent(this, WatchListActivity.class)); 
     } 

     return super.onOptionsItemSelected(item); 
    } 

} 

Код xml для представления позиции выглядит так:

<ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/item_icon" 
    android:src="@mipmap/ic_launcher" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="50dp" 
    android:layout_marginBottom="20dp"/> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:text="Make shown here" 
    android:id="@+id/item_txtMake" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:text="2000" 
    android:id="@+id/item_txtYear" 
    android:layout_below="@+id/item_icon" 
    android:layout_centerHorizontal="true" 
    android:layout_marginBottom="20dp"/> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceMedium" 
    android:text="Condition shown Here" 
    android:id="@+id/item_txtCondition" 
    android:layout_below="@+id/item_txtYear" 
    android:layout_centerHorizontal="true" /> 

<Button 
    style="?android:attr/buttonStyleSmall" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Buy Car online!" 
    android:id="@+id/item_button" 
    android:layout_below="@+id/item_txtCondition" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="25dp" /> 

<Button 
    style="?android:attr/buttonStyleSmall" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="add Car to WatchList" 
    android:onClick="addCarToWatchList" 
    android:id="@+id/item_watchlist_button" 
    android:layout_alignTop="@+id/item_icon" 
    android:layout_toRightOf="@+id/item_button" 
    android:layout_toEndOf="@+id/item_button" /> 

(Сначала: не путайте ссылки www.google.com для кнопок или одного и того же изображения (ic_launcher) для каждого автомобиля, я использовал его только для тестирования моего кода. Кнопка есть, чтобы добраться до ссылки, где вы можете купить автомобиль, например.)

Итак, все в порядке. Я могу запустить приложение без ошибок. Все кнопки работают. Я получаю ListView на моем MainActivity с различными автомобилями и на ToolBar У меня есть значок, который я могу щелкнуть и перейти на WatchList. Все так, как я хочу.

Но я не могу найти решение для своего следующего шага.

Во-первых: Я хочу добавить еще одну кнопку в мой item_view.xml. Это должно быть похоже на «Add to WatchList» -Button. Если я нажму кнопку «Эта кнопка», необходимо добавить элемент автомобиля к ListView операции WatchList. (The ListView в WatchList класса еще не существует)

Второе: Если элемент добавляется к WatchList, он должен быть собственный макет (собственный item_watchlist_view.xml), который включает в себя только (например) наименование и изображение item_view.xml от MainActivity. Было бы также неплохо, если есть кнопка удаления на item_watchlist_view.xml, которая может быть использована для удаления автомобиля с WatchList, если я больше не хочу его в своем WatchList.

Так что в основном приложение должно работать как «система корзины покупок», но разница в том, что у меня есть только автомобили, как продукты, и я могу добавить их в WatchList или FavoriteList («Корзина покупок»).

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

Было бы хорошо, если кто-то может дать мне подробный ответ!

Спасибо .. и извините за мой плохой английский!

+0

Как правило, вы должны сделать класс 'WatchList', включает в себя список в этом классе, и передать этот класс вашей второй активности. Затем используйте адаптер для доступа к информации в классе 'WatchList', чтобы заполнить ListView во втором действии. –

+0

Спасибо за ответ.Я видел подобное решение на форуме раньше, но я не могу решить свою проблему с этим ответом. – androidJava

+0

В чем проблема с этим решением? –

ответ

1

Чтобы передать параметры в новую операцию, вызовите его, вызывая

Intent intent = new Intent(this, WatchListActivity.class); 
Bundle b = new Bundle(); 
b.putInt("key", 1); //Your id 
intent.putExtras(b); //Put your id to your next Intent 
startActivity(intent);