I am trying to add a spinner object inside each item of a recyclerview.
I think the problem is that in OnCreate the setContentView(R.layout.activity_modify_list2) is referring to the xml file that contains the recyclerview:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify_list2);
initView();
}
Because of this, the createSpinner() method is looking for the spinner in that file rather than the xml file for the individual recyclerview item, giving a null object reference error:
private Spinner CreateSpinner() {
Spinner staticSpinner = findViewById(R.id.spinner);
... }
Full java file for the page:
public class ModifyListActivity extends Activity {
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify_list2);
initView();
}
private void initView() {
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewModifyList);
createList();
}
private void createList() {
ArrayList<ModifyListPageItem> items = new ArrayList<>();
ModifyListPageItem item;
item = new ModifyListPageItem();
item.setTitle("Resident Evil Games");
item.setDescription("Ranking all Resident Evil games");
items.add(item);
item = new ModifyListPageItem();
item.setRank("1.");
item.setSpinner(CreateSpinner());
items.add(item);
item = new ModifyListPageItem();
item.setRank("2.");
item.setSpinner(CreateSpinner());
items.add(item);
item = new ModifyListPageItem();
item.setRank("3.");
item.setSpinner(CreateSpinner());
items.add(item);
// set adapter
ModifyListPageAdapter adapter = new ModifyListPageAdapter(this, items);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
private Spinner CreateSpinner() {
Spinner staticSpinner = findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter
.createFromResource(this, R.array.resident_evil_games,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
staticAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
staticSpinner.setAdapter(staticAdapter);
return staticSpinner;
}
}
Full Java file for adapter
public class ModifyListPageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static int TYPE_HEADER = 1;
private static int TYPE_ITEM = 2;
private Context context;
private ArrayList<ModifyListPageItem> items;
public ModifyListPageAdapter(Context context, ArrayList<ModifyListPageItem> items) {
this.context = context;
this.items = items;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
if (viewType == TYPE_HEADER) {
view = LayoutInflater.from(context).inflate(R.layout.item_modlist_header, parent, false);
return new HeaderViewHolder(view);
}
else {
view = LayoutInflater.from(context).inflate(R.layout.item_modlist_object, parent, false);
return new ItemViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == TYPE_HEADER)
((HeaderViewHolder)holder).SetHeaderDetails(items.get(position));
else
((ItemViewHolder)holder).SetItemDetails(items.get(position));
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public int getItemViewType(int position) {
if (TextUtils.isEmpty(items.get(position).getRank())) {
return TYPE_HEADER;
}
else
return TYPE_ITEM;
}
class HeaderViewHolder extends RecyclerView.ViewHolder {
private TextView txtTitle;
private TextView txtDescription;
public HeaderViewHolder(#NonNull View itemView) {
super(itemView);
txtTitle = itemView.findViewById(R.id.txtModListTitle);
txtDescription = itemView.findViewById(R.id.txtModListDescription);
}
private void SetHeaderDetails(ModifyListPageItem item) {
txtTitle.setText(item.getTitle());
txtDescription.setText(item.getDescription());
}
}
class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView txtRank;
private Spinner spinner;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
txtRank = itemView.findViewById(R.id.modlist_rank);
spinner = itemView.findViewById(R.id.spinner);
}
private void SetItemDetails(ModifyListPageItem item) {
txtRank.setText(item.getRank());
spinner.setOnItemClickListener(spinner.getOnItemClickListener());
}
}
}
XML file for the page layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ModifyListActivity">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bottom_navigation"
app:itemBackground="#color/colorPrimary"
app:itemTextColor="#drawable/selector"
app:itemIconTint="#drawable/selector"
app:menu="#menu/menu_navigation"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerViewModifyList"/>
</RelativeLayout>
XML File for the recyclerview item layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:padding="8dp"
tools:context=".MainActivity">
<TextView
android:id="#+id/modlist_rank"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="1."
android:textColor="#000000"
android:textSize="38dp" />
<Spinner
android:id="#+id/spinner"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp" />
</LinearLayout>
Related
Hi I am completing a school project, and I need the background of a list item to be red with white text if the urgent switch is on. Currently, if I add an item with the urgent switch all of the background of the list view changes. I seen somewhere someone said to use an array, but when I tried that block of code it wouldn't work. Thanks in advance!
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="576dp"
android:layout_columnSpan="3"
android:focusableInTouchMode="true"
android:isScrollContainer="true">
</ListView>
<EditText
android:id="#+id/editText"
android:layout_width="209dp"
android:layout_height="wrap_content"
android:layout_weight="0"
android:hint="#string/typeHere"
android:textSize="20dp" />
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="1"
android:layout_column="1"
android:layout_weight="0"
android:text="#string/urgent" />
<Button
android:id="#+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="1"
android:layout_column="2"
android:layout_weight="0"
android:text="#string/add" />
</GridLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/to_do_TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Testing"
android:textSize="25dp" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Button buttonAdd;
Boolean urgent = false;
EditText editText;
ListAdapter adapter;
ListView myListView;
Switch switch1;
ArrayList<String> itemList = new ArrayList<String>( Arrays.asList("Clean Bathroom","Buy Apples","Buy Bananas" ));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//declare variables
buttonAdd = findViewById(R.id.buttonAdd);
editText = findViewById(R.id.editText);
switch1 = findViewById(R.id.switch1);
ListView myListView = findViewById(R.id.listView);
myListView.setAdapter(adapter = new ListAdapter());
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemList.add(editText.getText().toString());
editText.setText("");
//also tried setting value you here and using in getView
if(switch1.isChecked()){
urgent = true;
} else{
urgent = false;
}adapter.notifyDataSetChanged();
}
});
}
// adapter class
class ListAdapter extends BaseAdapter{
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int position) {
return itemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View old, ViewGroup parent) {
View newView =old;
LayoutInflater inflater = getLayoutInflater();
if(newView==null){
newView = inflater.inflate(R.layout.item,parent,false);
}
TextView textview= newView.findViewById(R.id.to_do_TextView);
textview.setText(getItem(position).toString());
if(switch1.isChecked()){
textview.setBackgroundColor(Color.RED);
textview.setText(getItem(position).toString());
}return newView;
}
//to do row class
class ToDoItem {
String name;
Boolean urgent;
}}}
This happen because you use a global variable Boolean urgent to all items in list.
You need send to ListAdapter the information if is urgent with a String doing use of class ToDoItem like this:
itemList.add(new ToDoItem(itemList.add(editText.getText().toString()), switch1.isChecked()));
the full code would be:
public class MainActivity extends AppCompatActivity {
Button buttonAdd;
EditText editText;
ListAdapter adapter;
ListView myListView;
Switch switch1;
//Create list
ArrayList<ToDoItem> itemList = new ArrayList<>();
//add data
itemList.add(new ToDoItem("Clean Bathroom", false);
itemList.add(new ToDoItem("Buy Apples", false);
itemList.add(new ToDoItem("Buy Bananas", true);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//declare variables
buttonAdd = findViewById(R.id.buttonAdd);
editText = findViewById(R.id.editText);
switch1 = findViewById(R.id.switch1);
ListView myListView = findViewById(R.id.listView);
myListView.setAdapter(adapter = new ListAdapter());
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Here set to list a item with String and boolean
itemList.add(new ToDoItem(itemList.add(editText.getText().toString()), switch1.isChecked()));
editText.setText("");
adapter.notifyDataSetChanged();
}
});
}
// adapter class
class ListAdapter extends BaseAdapter{
#Override
public int getCount() {
return itemList.size();
}
//Here get a item like ToDoItem
#Override
public ToDoItem getItem(int position) {
return itemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View old, ViewGroup parent) {
View newView =old;
LayoutInflater inflater = getLayoutInflater();
if(newView==null){
newView = inflater.inflate(R.layout.item,parent,false);
}
TextView textview= newView.findViewById(R.id.to_do_TextView);
//Here get a name
textview.setText(getItem(position).name);
if(getItem(position).urgent){
textview.setBackgroundColor(Color.RED);
}
return newView;
}
}
//Class that have the information on items
class ToDoItem {
String name;
Boolean urgent;
public ToDoItem(String name, Boolean urgent) {
this.name = name;
this.urgent = urgent;
}
}
}
I have some doubts about how to solve the doubt about how to click on a RecyclerView and change image from another activity, such as MainActivity.
In the image you can see what I'm trying to do. I have a total of 6 images, 3 Small images and another 3 Large images.
In the footer of MainActivity I have the ReciclerView that loads the 3 small images, I want that when they click for example to the image_Small_2/item_Small_2, that replaces the image that is in the center by the image_Large_2/item_Large_2.
I don't know if I'm explaining myself well, I leave you a screenshot and the code to see if you can give me a hand. Thanks in advance. P.S. I use the glide library to load the images.
My Adapter RecyclerView
public class AdaptadorX extends RecyclerView.Adapter<AdaptadorX.ViewHolder> {
private ArrayList<Items> itemsLi;
private Context context;
public static class ViewHolder extends RecyclerView.ViewHolder{
public ImageView idSrcImagen;
public ViewHolder(#NonNull View itemView) {
super(itemView);
idSrcImagen = itemView.findViewById(R.id.idImagen);
}
}
public AdaptadorX(ArrayList<Items> itemsListado, Context context_L){
itemsLi = itemsListado;
context = context_L;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_item, parent, false);
ViewHolder content = new ViewHolder(view);
return content;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
final Items contarItems = itemsLi.get(position);
Glide.with(context).load(contarItems.getxNombre_imagen()).into(holder.idSrcImagen);
holder.idSrcImagen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Mensaje_AdaptadorX.java", "Mi Posicion FOTO es: "+String.valueOf(position));
}
});
}
#Override
public int getItemCount() {
Log.d("Mensaje_Size_Tamaño", String.valueOf(itemsLi.size()));
return itemsLi.size();
}
}
Class Items
public class Items {
private String xNombre_imagen;
public Items (String nombre_imagen_M){
xNombre_imagen = nombre_imagen_M;
}
public String getxNombre_imagen() {
return xNombre_imagen;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
public ImageView idImgHead;
private ArrayList<Items> items;
private RecyclerView idRecyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
idRecyclerView = findViewById(R.id.idRecyclerView);
idImgHead = findViewById(R.id.idImgHead);
Glide.with(this).load("https://www.midominio.com/Imagen_GRANDE_head_01.jpg").into(idImgHead); //IMAGE BIG
listadoXhead();
}
private void listadoXhead() {
ArrayList<Items> items = new ArrayList<>();
items.add(new Items("https://www.midominio.com/Imagen_Pequeña_head_01.jpg")); //IMAGE Small
items.add(new Items("https://www.midominio.com/Imagen_Pequeña_head_02.jpg")); //IMAGE Small
items.add(new Items("https://www.midominio.com/Imagen_Pequeña_head_03.jpg")); //IMAGE Small
idRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
((LinearLayoutManager) layoutManager).setOrientation(RecyclerView.HORIZONTAL);
adapter = new AdaptadorX(items, MainActivity.this);
idRecyclerView.setLayoutManager(layoutManager);
idRecyclerView.setAdapter(adapter);
}
}
activity_main
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/idImgHead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:scaleType="fitCenter"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#mipmap/ic_launcher" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/idRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
activity_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/idImagen"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/ic_launcher_foreground"
android:onClick="accionBoton"/>
</LinearLayout>
Example Image Here
You need to implement an interface listener in your activity and pass it to your adapter. Add this to your adapter and pass it through the constructor
interface OnImageClickListener{
void onSelected(String url);
}
Your whole adapter should look like this.
public class AdaptadorX extends RecyclerView.Adapter<AdaptadorX.ViewHolder> {
private ArrayList<Items> itemsLi;
private Context context;
pruvate OnImageClickListener listener;
interface OnImageClickListener{
void onSelected(String url);
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public ImageView idSrcImagen;
public ViewHolder(#NonNull View itemView) {
super(itemView);
idSrcImagen = itemView.findViewById(R.id.idImagen);
}
}
public AdaptadorX(ArrayList<Items> itemsListado, Context context_L, OnImageClickListener listener){
itemsLi = itemsListado;
context = context_L;
this.listener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_item, parent, false);
ViewHolder content = new ViewHolder(view);
return content;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
final Items contarItems = itemsLi.get(position);
Glide.with(context).load(contarItems.getxNombre_imagen()).into(holder.idSrcImagen);
holder.idSrcImagen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onSelected(contarItems.getxNombre_imagen())
}
});
}
#Override
public int getItemCount() {
Log.d("Mensaje_Size_Tamaño", String.valueOf(itemsLi.size()));
return itemsLi.size();
}
}
And in your Activity you implement this interface and pass it to the adapter.
public class MainActivity extends AppCompatActivity implements OnImageClickListener {
public ImageView idImgHead;
private ArrayList<Items> items;
private RecyclerView idRecyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
idRecyclerView = findViewById(R.id.idRecyclerView);
idImgHead = findViewById(R.id.idImgHead);
Glide.with(this).load("https://www.midominio.com/Imagen_GRANDE_head_01.jpg").into(idImgHead); //IMAGE BIG
listadoXhead();
}
#Override
public onSelected(String url) {
Glide.with(this).load(url).into(idImgHead);
}
private void listadoXhead() {
ArrayList<Items> items = new ArrayList<>();
items.add(new Items("https://www.midominio.com/Imagen_Pequeña_head_01.jpg")); //IMAGE Small
items.add(new Items("https://www.midominio.com/Imagen_Pequeña_head_02.jpg")); //IMAGE Small
items.add(new Items("https://www.midominio.com/Imagen_Pequeña_head_03.jpg")); //IMAGE Small
idRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
((LinearLayoutManager) layoutManager).setOrientation(RecyclerView.HORIZONTAL);
adapter = new AdaptadorX(items, MainActivity.this, this);
idRecyclerView.setLayoutManager(layoutManager);
idRecyclerView.setAdapter(adapter);
}
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
super.onNotificationRemoved(sbn);
}
public List<String> getText(Notification notification) {
if (null == notification) {
return null;
}
RemoteViews views = notification.bigContentView;
if (views == null) {
views = notification.contentView;
}
if (views == null) {
return null;
}
How to put this code in android list view
to show notifications in list.
also provide xml layout for it.
First create a XML file my_list_view.xml for your simple ListView like this
<ListView
android:id="#+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"/>
Then create another xml file row_view.xml which will be the layout of each row in your ListView
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/title"
android:textSize="25sp"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<TextView
android:id="#+id/subTitle"
android:textSize="20sp"
android:layout_below="#+id/title"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</RelativeLayout>
Your next step is to create a CustomAdapter to properly inflate your ListView with notifications
public class CustomAdapter extends BaseAdapter {
Context context;
String titles[];
String subTitles[];
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, String[] titles, String[] subTitles)
{
this.context = context;
this.titles = titles;
this.subTitles=subTitles;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return titles.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.row_view, null);
Textview tv1=(TextView)view.findViewById(R.id.title);
Textview tv2=(TextView)view.findViewById(R.id.subTitle);
tv1.setText(titles[i]);
tv2.setText(subTitles[i]);
return view;
}
}
and finally in your MainActivity.java do the following
String notTitles[] = YOUR_NOTIFICATION_TITLES;
String notSubTitles[]=YOUR_NOTIFICATION_SUBTITLES;
ListView simpleList= (ListView) findViewById(R.id.simpleListView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), notTitles, notSubTitles);
simpleList.setAdapter(customAdapter);
that's it. :)
I want to add card style in my app like this
i use in my app mysql database so i need to make like this cards and put my data from database in it now i use ListView with this code
public void listAllItme() {
ListAdapter lA = new listAdapter(listitems);
listView.setAdapter(lA);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent open = new Intent(R_arabic.this, rewaya_show.class);
open.putExtra("name", listitems.get(position).name);
open.putExtra("url", listitems.get(position).url);
open.putExtra("img", listitems.get(position).img);
open.putExtra("num", listitems.get(position).num);
startActivity(open);
}
}
});
}
class listAdapter extends BaseAdapter {
ArrayList<listitem_gib> lista = new ArrayList<listitem_gib>();
public listAdapter(ArrayList<listitem_gib> lista) {
this.lista = lista;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int position) {
return lista.get(position).name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.row_item_gib, null);
TextView name = (TextView) view.findViewById(R.id.textView_gib);
ImageView img = (ImageView) view.findViewById(R.id.imageView_gib);
TextView num = (TextView) view.findViewById(R.id.textView_gib2);
TextView size = (TextView) view.findViewById(R.id.textView_gib3);
name.setText(lista.get(position).name);
num.setText(lista.get(position).num);
size.setText(lista.get(position).size);
Picasso.with(R_arabic.this).load("http://grassyhat.com/android/image/" + lista.get(position).img).into(img);
return view;
}
}
first i want to know how i can make like this card style
second how i can use this code with card menu not listview
sorry im new in android and sorry for my bad english
What do you mean by card menu? because the example in the image is a recyclerview with a cardview item, you can achieve this by doing something like this
This will be your activity
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
//Just your list of objects, in your case the list that comes from the db
List<Items> itemsList = new ArrayList<>();
CardAdapter adapter = new CardAdapter(this, itemsList);
//RecyclerView needs a layout manager in order to display data so here we create one
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
//Here we set the layout manager and the adapter to the listview
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
Inside the layout file you just have to place the recyclerview like this
<RelativeLayout
android:id="#+id/activity_main"
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"
tools:context="jsondh.myapplication.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Then your adapter will be something like this
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {
private List<Items> itemsList;
private Activity activity;
public CardAdapter(Activity activity, List<Items> items){
this.activity = activity;
this.itemsList = items;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = activity.getLayoutInflater().inflate(R.layout.cardview_layout, parent, false);
return new CardViewHolder(itemView);
}
#Override
public void onBindViewHolder(CardViewHolder holder, int position) {
//Here you bind your views with the data from each object from the list
}
#Override
public int getItemCount() {
return itemsList.size();
}
public class CardViewHolder extends RecyclerView.ViewHolder {
public ImageView bookImage;
public TextView bookLabel01, bookLabel02;
public CardViewHolder(View itemView) {
super(itemView);
bookImage = (ImageView)itemView.findViewById(R.id.image);
bookLabel01 = (TextView)itemView.findViewById(R.id.label01);
bookLabel02 = (TextView)itemView.findViewById(R.id.label02);
}
}
And the last one will be the layout from each item on the list, like this
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp">
<android.support.v7.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardElevation="15dp"
app:cardBackgroundColor="#3369Ed">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/image"
android:layout_width="150dp"
android:layout_height="130dp"/>
<TextView
android:id="#+id/label01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label"
android:layout_gravity="right"
android:padding="5dp"
android:textColor="#ffffff"/>
<TextView
android:id="#+id/label02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LongerLabel"
android:layout_gravity="right"
android:padding="5dp"
android:textColor="#ffffff"/>
</LinearLayout>
</android.support.v7.widget.CardView>
You also have to add this to your gradle file:
compile 'com.android.support:recyclerview-v7:25.0.0'
compile 'com.android.support:cardview-v7:25.0.0'
Hope it helps!
It's pretty simple. You will have to use a RecyclerView with GridLayoutManager and add a cardView to it.
Then, use an Adapter and ViewHolder to feed the data.
I suggest you to check this out:
https://developer.android.com/training/material/lists-cards.html
I am working on Android project. I follow tutorial from http://www.vogella.com/articles/AndroidSQLite/article.html but I stuck on something. Tutorial shows how to use Class with 1 String object. I am working with 2 String objects. So I changed few things (add new String to my class, change layout.simple_list_item_1 to android.R.layout.simple_list_item_2 etc.) And now the question is - how to make something to get Stoliki class objects (override toString() gives me only 1 item, so It's useless).
Class Stoliki
public class Stoliki {
private long id;
private String numer;
private String opis;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNumer() {
return numer;
}
public void setNumer(String numer) {
this.numer = numer;
}
public String getOpis() {
return opis;
}
public void setOpis(String opis) {
this.opis = opis;
}
}
Activity
import android.app.ListActivity;
import android.os.Bundle;
import java.util.List;
import java.util.Random;
import android.view.View;
import android.widget.ArrayAdapter;
public class FirstGridPage extends ListActivity {
private StolikiDataSource datasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_list_stoliki);
datasource = new StolikiDataSource(this);
datasource.open();
List<Stoliki> values = datasource.getAllStoliki();
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Stoliki> adapter = new ArrayAdapter<Stoliki>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Stoliki> adapter = (ArrayAdapter<Stoliki>) getListAdapter();
Stoliki stolik = null;
switch (view.getId()) {
case R.id.add:
String[] stoliki_numer = new String[] { "1", "2", "3" };
String[] stoliki_opis = new String[] { "Czerwony", "Niebieski", "Zielony" };
int nextInt = new Random().nextInt(3);
// Save the new comment to the database
stolik = datasource.createStolik(stoliki_numer[nextInt], stoliki_opis[nextInt]);
adapter.add(stolik);
break;
case R.id.delete:
if (getListAdapter().getCount() > 0) {
stolik = (Stoliki) getListAdapter().getItem(0);
datasource.deleteStolik(stolik);
adapter.remove(stolik);
}
break;
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
http://www.youtube.com/watch?v=wDBM6wVEO70. Listview talk by Romain guy( android developer at google).
Main.xml
<ListView android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:focusableInTouchMode="false"
android:listSelector="#android:color/transparent"
android:layout_weight="2"
android:headerDividersEnabled="false"
android:footerDividersEnabled="false"
android:dividerHeight="8dp"
android:divider="#000000"
android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>
</LinearLayout>
Customw row. row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="#ffffff"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:background="#drawable/itembkg"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="TextView" />
</LinearLayout>
public class CustomListView extends Activity {
/** Called when the activity is first created. */
ListView lv1;
Customlistadapter cus;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Button b= (Button) findViewById(R.id.remove);
lv1 = (ListView) findViewById(R.id.list);
cus= new Customlistadapter(this);
lv1.setAdapter(cus);
}
}
Custom list adapter. Inflate custom layout for each row.
public class Customlistadapter extends ArrayAdapter {
private LayoutInflater mInflater;
Context c;
public Customlistadapter(CustomListView customListView) {
super(customListView, 0);
// TODO Auto-generated constructor stub
this.mInflater = LayoutInflater.from(customListView);
c=customListView;
}
public int getCount() {
return 20; // number of listview rows.
}
public Object getItem(int arg0) {
return arg0;
}
public long getItemId(int arg0) {
return arg0;
}
public View getView(final int arg0, View arg1, ViewGroup arg2) {
final ViewHolder vh;
vh= new ViewHolder();
if(arg1==null )
{
arg1=mInflater.inflate(R.layout.row, arg2,false);
vh.tv1= (TextView)arg1.findViewById(R.id.textView1);
vh.tv2= (TextView)arg1.findViewById(R.id.textView2);
}
else
{
arg1.setTag(vh);
}
vh.tv1.setText("hello");
vh.tv2.setText("hello");
return arg1;
}
static class ViewHolder //use a viewholder for smooth scrolling and performance.
{
TextView tv1,tv2;
}
}
Edit:
Your activity will have a listview. This is set in oncreate setContentView(R.layout.activity_main);. The main layout will have a listview. You set the adapter of listview as listview.setAdapter(youradapter);
Then listview will have custom layout ie row.xml inflated for each row item. You custom adapter for listview is where the row.xml is inflated. You defined your class CustomAdapter which extends ArrayAdapter. You override a set of methods.
getCount() --- size of listview.
getItem(int position) -- returns the position
getView(int position, View convertView, ViewGroup parent)
// position is the position in the listview.
//convertview - view that is tobe inflated
// you will return the view that is infated.
You will have to use a viewholder for smooth scrolling and performance. Imagine 1000 rows is lstview with images it may cause memory exceptions. One way to get rid of this is to recycle views. The visible views(rows) are not recycled. The video in the link at the top has a detail explanation on the topic
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#0095FF">
<ListView android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:focusableInTouchMode="false"
android:listSelector="#android:color/transparent"
android:layout_weight="2"
android:headerDividersEnabled="false"
android:footerDividersEnabled="false"
android:dividerHeight="8dp"
android:divider="#000000"
android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>
</LinearLayout>
row.xml (layout inflated for each listview row)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Header" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_gravity="center"
android:text="TextView" />
</LinearLayout>
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView ll = (ListView) findViewById(R.id.list);
CustomAdapter cus = new CustomAdapter();
ll.setAdapter(cus);
}
class CustomAdapter extends BaseAdapter
{
LayoutInflater mInflater;
public CustomAdapter()
{
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 30;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder vh;
vh= new ViewHolder();
if(convertView==null )
{
convertView=mInflater.inflate(R.layout.row, parent,false);
vh.tv2= (TextView)convertView.findViewById(R.id.textView2);
vh.tv1= (TextView)convertView.findViewById(R.id.textView2);
}
else
{
convertView.setTag(vh);
}
vh.tv1.setText("my text");
vh.tv2.setText("Postion = "+position);
return convertView;
}
class ViewHolder
{
TextView tv1,tv2;
}
}
}