2016-05-01 3 views
1

Я пытаюсь добавить новый вид карты/новую карту thingy (извините, что я новичок) в моем приложении. прямо сейчас, все работает отлично, но как бы добавить больше? Я также хотел бы знать, как это сделать по щелчку FAB. Вот мой кодКак создать новый CardView?

public class WeatherListAdapter extends RecyclerView.Adapter<WeatherListAdapter.ViewHolder>{ 

    private List<WeatherData> weatherDataList; 

    @Override 
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     //? 
     View view1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_weather_card,parent,false); 
     View view2 = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_weather_card,parent,false); 
     return new ViewHolder(view2); 
    } 

    @Override 
    public void onBindViewHolder(ViewHolder holder, int position) { 
     WeatherData weatherData = this.weatherDataList.get(position); 
     holder.locationTextView.setText(weatherData.getName()); 
     holder.tempTextView.setText("Temperature: "+weatherData.getWeatherDetails().getTemperature()); 
     holder.humidTextView.setText("Humidity: "+ weatherData.getWeatherDetails().getHumidity()); 


    } 

    @Override 
    public int getItemCount() { 
     return this.weatherDataList.size(); 
    } 

    protected static class ViewHolder extends RecyclerView.ViewHolder{ 

     public TextView locationTextView; 
     public TextView tempTextView; 
     public TextView humidTextView; 
     public ViewHolder(View v){ 
      super(v); 
      locationTextView = (TextView) v.findViewById(R.id.locationTextView); 
      tempTextView = (TextView) v.findViewById(R.id.tempTextView); 
      humidTextView= (TextView) v.findViewById(R.id.humidText); 
     } 




    } 

    public WeatherListAdapter(List<WeatherData> weatherDataList){ 
     this.weatherDataList = weatherDataList; 

    } 
} 

Если мне нужно добавить больше, чтобы помочь вам разобраться, просто оставьте комментарий. Благодаря! WeatherListActivity-

private RecyclerView recyclerView; 
List<WeatherData> mWeatherDataList; 
WeatherListAdapter mAdpapter; 

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

    recyclerView = (RecyclerView) findViewById(R.id.recyclerView); 
    recyclerView.setLayoutManager(new LinearLayoutManager(this)); 

    mWeatherDataList = new ArrayList<WeatherData>(); 








    final WeatherApiManager weatherApiManager = new WeatherApiManager(); 
    weatherApiManager.getWeatherByCoordinate(35.744644099999995, -78.86395929999999, new WeatherCallback() { 
     @Override 
     public void weatherDownloadCompleted(boolean success, WeatherData weatherData) { 
      List<WeatherData> weatherDataList = new ArrayList<WeatherData>(); 
      // weatherDataList.add(weatherData); 
      // weatherDataList.add(weatherData); 

      mAdpapter = new WeatherListAdapter(weatherDataList); 






      //why does this have to be in here? 
      recyclerView.setAdapter(mAdpapter); 

     } 
    }); 



    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 

    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 

      final WeatherApiManager weatherApiManager = new WeatherApiManager(); 
      weatherApiManager.getWeatherByCoordinate(35.744644099999995, -78.86395929999999, new WeatherCallback() { 
       @Override 
       public void weatherDownloadCompleted(boolean success, WeatherData weatherData) { 
        List<WeatherData> weatherDataList = new ArrayList<WeatherData>(); 

        weatherDataList.add(weatherData); 

        mAdpapter = new WeatherListAdapter(weatherDataList); 


        //why does this have to be in here? 
        recyclerView.setAdapter(mAdpapter); 


       } 
      }); 

      updateUI(); 


     } 
    }); 


} 
+0

Вы пытаетесь добавить только одну карту или динамическое число или карты? –

+0

1 за раз, но я бы хотел, чтобы пользователь мог добавить его с помощью FAB –

ответ

2

для того, чтобы использовать CardView в вашем RecyclerView (а затем прикрепить TextViews вы имели ранее) I сделал бы omething так:

public class WeatherListAdapter extends RecyclerView.Adapter<WeatherListAdapter.ViewHolder>{ 

    private List<WeatherData> weatherDataList; 

    public TextView locationTextView; 
    public TextView tempTextView; 
    public TextView humidTextView; 

    @Override 
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     // Here we are inflating the CardView 
     View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_weather_card, parent, false); 
     return new ViewHolder(view); 
    } 

    @Override 
    public void onBindViewHolder(ViewHolder holder, int position) { 
     WeatherData weatherData = this.weatherDataList.get(position); 
     CardView cardView = holder.cardView; 

     // We then add these items to each CardView 
     locationTextView = (TextView) cardView.findViewById(R.id.locationTextView); 
     tempTextView = (TextView) cardView.findViewById(R.id.tempTextView); 
     humidTextView= (TextView) cardView.findViewById(R.id.humidText); 

     locationTextView.setText(weatherData.getName()); 
     tempTextView.setText("Temperature: "+weatherData.getWeatherDetails().getTemperature()); 
     humidTextView.setText("Humidity: "+ weatherData.getWeatherDetails().getHumidity()); 
    } 

    @Override 
    public int getItemCount() { 
     return this.weatherDataList.size(); 
    } 

    protected static class ViewHolder extends RecyclerView.ViewHolder{ 
     public CardView cardView; 

     public ViewHolder(View v){ 
      super(v); 
      // Each ViewHolder only has a CardView (even though that CardView has child TextViews 
      cardView = (CardView) v; 
     } 

    } 

    public WeatherListAdapter(List<WeatherData> weatherDataList){ 
     this.weatherDataList = weatherDataList; 
    } 
} 

Тогда вы просто должны убедиться, что adapter_weather_card.xml в верстку имеет <TextView> элементы для locationTextView, tempTextView и humidTextView поэтому все они могут быть отображены на каждом CardView.

Sample активность Использование данного WeatherListAdapter

public class MainActivity extends AppCompatActivity { 

    RecyclerView mRecyclerView; 
    WeatherListAdapter mAdapter; 
    List<WeatherData> mList; 

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

     mList = new ArrayList<>(); 
     // Just a bunch of sample data we're using to populate the RecyclerView 
     mList.add(new WeatherData("Sacramento", "88", "60")); 
     mList.add(new WeatherData("Dallas", "96", "40")); 
     mList.add(new WeatherData("Orlando", "80", "85")); 
     mList.add(new WeatherData("Seattle", "68", "78")); 

     mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); 
     mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); 
     // In your WeatherListAdapater class you pass a List to the constructor, this is the 
     // list that contains all the WeatherData and the list we use to add new CardViews. 
     mAdapter = new WeatherListAdapter(mList); 
     mRecyclerView.setAdapter(mAdapter); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       // Adding a new item to our WeatherData list with the FAB 
       // This item will become a new CardView 
       // We can similarly remove CardViews by calling remove() 
       mList.add(new WeatherData("Boston", "67", "50")); 
       // Updating the UI after adding the CardView so it shows up 
       updateUI(); 
      } 
     }); 
    } 

    private void updateUI() { 
     // The list we passed to the mAdapter was changed so we have to notify it in order to update 
     mAdapter.notifyDataSetChanged(); 
    } 

} 

Пример XML для этой деятельности

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/recycler_view" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_centerInParent="true" 
     android:layout_margin="20dp"> 
    </android.support.v7.widget.RecyclerView> 

    <android.support.design.widget.FloatingActionButton 
     android:id="@+id/fab" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentEnd="true" 
     android:layout_alignParentRight="true" 
     android:layout_margin="@dimen/fab_margin" 
     android:src="@android:drawable/ic_menu_add"/> 

</RelativeLayout> 

Образец CardView XML

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v7.widget.CardView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="150dp" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_margin="10dp" 
    app:cardBackgroundColor="@android:color/holo_blue_light"> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:paddingRight="10dp" 
     android:paddingLeft="10dp" 
     android:paddingTop="10dp" 
     android:paddingBottom="10dp" 
     android:orientation="vertical"> 

     <TextView 
      android:id="@+id/locationTextView" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"/> 

     <TextView 
      android:id="@+id/tempTextView" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"/> 

     <TextView 
      android:id="@+id/humidText" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"/> 

    </LinearLayout> 

</android.support.v7.widget.CardView> 
+0

, но у меня есть ошибка. Мне жаль, если я не сделал себе достаточно ясно, но я хочу добавить несколько карточек (idk, если это правильное имя, но похоже, что это) друг под друга, и, в конечном счете, нажатие FAB. ты знаешь, как я это сделаю? Благодарю. –

+0

Какая ошибка у вас возникла? И вы пытаетесь создать RecyclerView с несколькими CardView? – apicellaj

+0

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

0

Простая карта View можно добавить с помощью CardView виджета в файле макета XML. Это пример реализации:

<!-- Root element of the XML Layout file --> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:card_view="http://schemas.android.com/apk/res-auto" 
    ... > 

    <!-- A CardView that contains a TextView --> 
    <android.support.v7.widget.CardView 
     xmlns:card_view="http://schemas.android.com/apk/res-auto" 
     android:id="@+id/card_view" 
     android:layout_gravity="center" 
     android:layout_width="200dp" 
     android:layout_height="200dp" 
     card_view:cardCornerRadius="4dp"> 

     <!-- Here goes the content of the card --> 
     <TextView 
      android:id="@+id/info_text" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" /> 

    </android.support.v7.widget.CardView> 
</LinearLayout> 

Вы также должны загрузить библиотеки для Android поддержки с помощью SDK менеджер, если вы их не имеют уже (вы можете найти их в каталоге «Extras» в нижней части из списка загружаемого контента), а затем добавить зависимость в вашей Gradle конфигурации:

dependencies { 
    ... 
    compile 'com.android.support:cardview-v7:21.0.+' 
} 

Источник: Android Developers website

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