When I change the color of a cardview which is inside a recyclerview, it changes color of other items also. How can I solve this problem.
Below is the part of the module where I am changing the background color :
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && mListener != null) {
mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
int position = recyclerView.getChildLayoutPosition(child);
child.setBackgroundColor(mContext.getResources().getColor(R.color.blue_light));
Toast.makeText(mContext, "Id " + String.valueOf(position), Toast.LENGTH_SHORT).show();
deleteItems.add(position);
}
}
});
}
The code for the adapter is given below :
public class DiaryAdapter extends RecyclerView.Adapter<DiaryAdapter.ViewHolder>{
List <DiaryInfo> mItems;
SQLiteDatabase mydatabase;
public DiaryAdapter() {
super();
mItems = new ArrayList <DiaryInfo> ();
mItems = MainActivity.diaryinfo;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.content_main, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
mydatabase = (MainActivity.mContext).openOrCreateDatabase("remember", android.content.Context.MODE_PRIVATE, null);
// While changing database information here change at Itemadd's done button listener also!
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS memories_pics(id VARCHAR PRIMARY KEY, path VARCHAR)");
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
try {
DiaryInfo info = mItems.get(i);
viewHolder.desc.setText(Html.fromHtml((info.getDesc()).replaceAll("''", "\"")));
// Modifying date to readable format
String tempDate = info.getDate();
Locale locale = (MainActivity.mContext).getResources().getConfiguration().locale;
String[] temp = tempDate.split("/"); // Splitting date dd/mm/yyyy
int month = Integer.valueOf(temp[1]);
DateFormatSymbols symbols = new DateFormatSymbols(locale);
String[] monthNames = symbols.getMonths();
String currentMonth = monthNames[month - 1];
viewHolder.date.setText(currentMonth + " " + temp[0]);
String id = info.getThumbnail();
String path = ""; // Final path of the thumbnail
Cursor cursor = mydatabase.rawQuery("SELECT * FROM memories_pics WHERE id=\'" + id + "\' LIMIT 1", null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
path = cursor.getString(cursor
.getColumnIndex("path"));
cursor.moveToNext();
break;
}
}
cursor.close();
File file = null;
// Either load image from user clicked images or a default image
if ((String.valueOf(path.split("=")[0])).equals("")) {
Glide.with(MainActivity.mContext).load(R.drawable.default_pic).centerCrop().into(viewHolder.imgThumbnail);
} else {
file = new File(String.valueOf(path.split("=")[0])); // Load path in file
Glide.with(MainActivity.mContext).load(file).centerCrop().into(viewHolder.imgThumbnail);
}
}
catch (Exception e) {
}
}
#Override
public int getItemCount() {
return mItems.size();
}
public Object getItem(int pos) { return mItems.get(pos); }
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imgThumbnail;
public TextView date, desc;
public ViewHolder(View itemView) {
super(itemView);
imgThumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
date = (TextView)itemView.findViewById(R.id.date);
desc = (TextView)itemView.findViewById(R.id.description);
}
}
}
Below is the cardview layout :
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:scaleType="centerCrop"
android:src="#drawable/default_pic"/>
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/thumbnail"
android:maxLines="1"
android:padding="4dp"
android:text="Title"
android:textColor="#222"
android:textStyle="bold"
android:textSize="22sp"/>
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/date"
android:maxLines="3"
android:padding="4dp"
android:text="Description"
android:textColor="#666"
android:textSize="14sp"
android:ellipsize="end"/>
</RelativeLayout>
Please help!
Related
I am trying to build a listview which contains outlet address in 5 lines,along with a status indicator image and a button. The following is the functionality I am trying to build.
When the list text is clicked - I want to open a activity.
When the button (COMP) is clicked - I want to open a different activity.
The image (tickmark) is a status indicator to inform the user whether the activity in a outlet is complete or not.
The list is populated from a SqliteDatabase. On clicking the button, I want to take the reference of the outlet and show different attributes of the outlet.
How do I integrate the button into the list view.
I have written the following code so far:
LISTVIEW.XML
<?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="wrap_content"
android:padding="3dp"
android:background="#FFFFFF"
android:layout_marginLeft="2dp"
android:layout_marginBottom="2dp"
android:descendantFocusability="blocksDescendants"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageViewFlag"
android:layout_rowSpan="2"
android:layout_width="25dp"
android:layout_height="25dp"
android:scaleType="fitXY"
android:layout_marginTop="20dp"
android:foregroundGravity="center"
android:layout_gravity="center"
android:background="#drawable/compliance_foreground"
android:layout_row="0"
android:layout_column="0" />
<Button
android:id="#+id/complianceButton"
android:layout_width="70dp"
android:layout_height="35dp"
android:text="COMP"
android:textSize="12sp"
></Button>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="5dp"
>
<TextView
android:id="#+id/tvOutletNamealt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Outlet :"
android:textSize="15sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#04031A"
android:textAllCaps="true"
android:layout_columnWeight="1"
android:layout_row="0"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletAddress1alt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address1 :"
android:textSize="12sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="1"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletAddress2alt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address2 :"
android:textSize="12sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="2"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletCityalt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City :"
android:textSize="12sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="3"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletPhonealt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PhoneNumber :"
android:textSize="13sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="4"
android:layout_column="1" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class show_outlets_alt extends AppCompatActivity {
SQLiteHelper sqLiteHelper;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
AltOutletAdapter listAdapterOutlets ;
String lati;
String longi;
String projectName;
String usrname;
Button cButton;
ListView LISTVIEWOUTLETS;
ArrayList<String> Id_Array;
ArrayList<String> OutletName_Array;
ArrayList<String> OutletAddress1_Array;
ArrayList<String> OutletAddress2_Array;
ArrayList<String> City_Array;
ArrayList<String> Phone_Array;
ArrayList<String> ListViewClickItemArrayOutlets = new ArrayList<String>();
private String projectID;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_show_outlets_alt );
// Set toolbar for this screen
Toolbar sectoolbar = (Toolbar) findViewById( R.id.secondary_toolbar );
sectoolbar.setTitle("");
sectoolbar.setBackground(new ColorDrawable(getResources().getColor(R.color.primary_welcome_color)));
TextView main_title = (TextView) findViewById(R.id.secondary_toolbar_title);
main_title.setText("PROJECT LOCATIONS");
main_title.setTextColor( this.getResources().getColor( R.color.white ) );
setSupportActionBar( sectoolbar );
usrname = SaveSharedPreference.getUserName( show_outlets_alt.this );
projectID = SaveSharedPreference.getProjName( show_outlets_alt.this );
LISTVIEWOUTLETS = this.findViewById( R.id.listView2alt );
imageView = this.findViewById( R.id.imageViewFlag );
cButton = findViewById( R.id.complianceButton );
Id_Array = new ArrayList<>();
OutletName_Array = new ArrayList<>();
OutletAddress1_Array = new ArrayList<>();
OutletAddress2_Array = new ArrayList<>();
City_Array = new ArrayList<>();
Phone_Array = new ArrayList<>();
sqLiteHelper = new SQLiteHelper(this);
LISTVIEWOUTLETS.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
projectName = SaveSharedPreference.getProjName( show_outlets_alt.this );
String outletName = ListViewClickItemArrayOutlets.get(position).toString();
SaveSharedPreference.setOutletName( getApplicationContext(),outletName );
Intent intent = new Intent(getApplicationContext(), ShowOutletParams.class);
startActivityForResult( intent,1 );
}
} );
} //end of oncreate
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult( requestCode, resultCode, data );
if (resultCode == RESULT_OK) {
Intent refresh = new Intent( this, ShowDataActivity.class );
startActivityForResult(refresh,1);
this.finish();
}
}
#Override
protected void onResume() {
ShowSQLiteOutletdata();
super.onResume();
}
private void ShowSQLiteOutletdata() {
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
projectID = SaveSharedPreference.getProjName( show_outlets_alt.this );
cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+SQLiteHelper.TABLE_NAME1+" where pid = (select projectId from "+SQLiteHelper.TABLE_NAME+ " where ProjectName = '"+projectID+"'"+") and Status=1;", null);
Id_Array.clear();
OutletName_Array.clear();
OutletAddress1_Array.clear();
OutletAddress2_Array.clear();
City_Array.clear();
Phone_Array.clear();
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Id_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_ID)));
ListViewClickItemArrayOutlets.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_OutletName)));
OutletName_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_OutletName)));
OutletAddress1_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_outletAddress1)));
OutletAddress2_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_outletAddress2)));
City_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_city)));
Phone_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_phone)));
} while (cursor.moveToNext());
}
}
listAdapterOutlets = new AltOutletAdapter(show_outlets_alt.this,
Id_Array,
OutletName_Array,
OutletAddress1_Array,
OutletAddress2_Array,
City_Array,
Phone_Array
);
LISTVIEWOUTLETS.setAdapter(listAdapterOutlets);
cursor.close();
} //end of ShowSqliteOutletData
#Override
public void onBackPressed() {
super.onBackPressed();
Intent backIntent = new Intent(getApplicationContext(), ShowDataActivity.class);
startActivity(backIntent);
}
}//end of public class
AltOutletAdapter.java
public class AltOutletAdapter extends BaseAdapter {
Context context;
ArrayList<String> ID;
ArrayList<String> O_Name;
ArrayList<String> O_Address1;
ArrayList<String> O_Address2;
ArrayList<String> City;
ArrayList<String> Phone;
ArrayList<String> iButton;
public AltOutletAdapter(Context context, ArrayList<String> ID, ArrayList<String> o_Name, ArrayList<String> o_Address1, ArrayList<String> o_Address2, ArrayList<String> city, ArrayList<String> phone) {
this.context = context;
this.ID = ID;
O_Name = o_Name;
O_Address1 = o_Address1;
O_Address2 = o_Address2;
City = city;
Phone = phone;
}
#Override
public int getCount() {
return ID.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View child, ViewGroup parent) {
AltOutletAdapter.Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.alt_list_view, null);
holder = new AltOutletAdapter.Holder();
holder.O_Name = (TextView) child.findViewById(R.id.tvOutletNamealt);
holder.O_Address1 = (TextView) child.findViewById(R.id.tvOutletAddress1alt);
holder.O_Address2 = (TextView) child.findViewById(R.id.tvOutletAddress2alt);
holder.City = (TextView) child.findViewById(R.id.tvOutletCityalt);
holder.Phone = (TextView) child.findViewById(R.id.tvOutletPhonealt);
child.setTag(holder);
} else {
holder = (AltOutletAdapter.Holder) child.getTag();
}
holder.O_Name.setText(O_Name.get(position));
holder.O_Address1.setText(O_Address1.get(position));
holder.O_Address2.setText(O_Address2.get(position));
holder.City.setText(City.get(position));
holder.Phone.setText(Phone.get(position));
return child;
}
private class Holder {
TextView O_Name;
TextView O_Address1;
TextView O_Address2;
TextView City;
TextView Phone;
Button iButton;
ImageView imageView;
}
}
first I have question.
why don't you make Model for Items?
Anyway if you want to make click event by element, just add click listener in your adapter.
so Example is here
add id in your whole layout.
( android:id="#+id/layout" )
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="3dp"
android:background="#FFFFFF"
android:layout_marginLeft="2dp"
android:layout_marginBottom="2dp"
android:descendantFocusability="blocksDescendants">
...
add click listener in your adapter
public class AltOutletAdapter extends BaseAdapter {
Context context;
ArrayList<String> ID;
ArrayList<String> O_Name;
ArrayList<String> O_Address1;
ArrayList<String> O_Address2;
ArrayList<String> City;
ArrayList<String> Phone;
ArrayList<String> iButton;
public LinearLayout linearLayout;
public AltOutletClickListener altOutletClickListener;
public AltOutletAdapter(Context context, ArrayList<String> ID, ArrayList<String> o_Name, ArrayList<String> o_Address1, ArrayList<String> o_Address2, ArrayList<String> city, ArrayList<String> phone, AltOutletClickListener listener) {
this.context = context;
this.ID = ID;
O_Name = o_Name;
O_Address1 = o_Address1;
O_Address2 = o_Address2;
City = city;
Phone = phone;
altOutletClickListener = listener;
}
#Override
public int getCount() {
return ID.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View child, ViewGroup parent) {
AltOutletAdapter.Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.alt_list_view, null);
holder = new AltOutletAdapter.Holder();
holder.O_Name = (TextView) child.findViewById(R.id.tvOutletNamealt);
holder.O_Address1 = (TextView) child.findViewById(R.id.tvOutletAddress1alt);
holder.O_Address2 = (TextView) child.findViewById(R.id.tvOutletAddress2alt);
holder.City = (TextView) child.findViewById(R.id.tvOutletCityalt);
holder.Phone = (TextView) child.findViewById(R.id.tvOutletPhonealt);
holder.linearLayout = (LinearLayout) child.findViewById(R.id.layout);
holder.iButton = (Button) child.findViewById(R.id.complianceButton);
child.setTag(holder);
} else {
holder = (AltOutletAdapter.Holder) child.getTag();
}
holder.O_Name.setText(O_Name.get(position));
holder.O_Address1.setText(O_Address1.get(position));
holder.O_Address2.setText(O_Address2.get(position));
holder.City.setText(City.get(position));
holder.Phone.setText(Phone.get(position));
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.itemClickListener(v, position);
}
});
holder.iButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.imageClickListener(v, position);
}
});
return child;
}
private class Holder {
TextView O_Name;
TextView O_Address1;
TextView O_Address2;
TextView City;
TextView Phone;
Button iButton;
ImageView imageView;
LinearLayout linearLayout;
}
public interface AltOutletClickListener {
void itemClickListener(View v, int position);
void imageClickListener(View v, int position);
}
}
when you call adapter in java, add click event as params.
ArrayList<String> test = new ArrayList<>();
AltOutletAdapter altOutletAdapter = new AltOutletAdapter(MainActivity.this, test, test, test, test, test, test, new AltOutletAdapter.AltOutletClickListener() {
#Override
public void itemClickListener(View v, int position) {
// when click layout
}
#Override
public void imageClickListener(View v, int position) {
// when click button
}
});
I just tested and use this.
But I think make Model is better.
ArrayList<String> test = new ArrayList<>();
ArrayList<Model> test = new ArrayList<>(); // it is better
**UPDATE : make Model **
simply, I make your Model Example.
make Model file.
public class AltOutlet {
private String name;
private String address1;
private String address2;
private String city;
private String phone;
public AltOutlet(String name, String address1, String address2, String city, String phone) {
this.name = name;
this.address1 = address1;
this.address2 = address2;
this.city = city;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
change your adapter
public class AltOutletAdapter extends BaseAdapter {
Context context;
ArrayList<AltOutlet> altOutletArrayList;
public LinearLayout linearLayout;
public AltOutletClickListener altOutletClickListener;
public AltOutletAdapter(Context context, ArrayList<AltOutlet> altOutletList, AltOutletClickListener listener) {
this.context = context;
altOutletArrayList = altOutletList;
altOutletClickListener = listener;
}
#Override
public int getCount() {
return altOutletArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View child, ViewGroup parent) {
AltOutletAdapter.Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.alt_list_view, null);
holder = new AltOutletAdapter.Holder();
holder.O_Name = (TextView) child.findViewById(R.id.tvOutletNamealt);
holder.O_Address1 = (TextView) child.findViewById(R.id.tvOutletAddress1alt);
holder.O_Address2 = (TextView) child.findViewById(R.id.tvOutletAddress2alt);
holder.City = (TextView) child.findViewById(R.id.tvOutletCityalt);
holder.Phone = (TextView) child.findViewById(R.id.tvOutletPhonealt);
holder.linearLayout = (LinearLayout) child.findViewById(R.id.layout);
holder.iButton = (Button) child.findViewById(R.id.complianceButton);
child.setTag(holder);
} else {
holder = (AltOutletAdapter.Holder) child.getTag();
}
holder.O_Name.setText(altOutletArrayList.get(position).getName());
holder.O_Address1.setText(altOutletArrayList.get(position).getAddress1());
holder.O_Address2.setText(altOutletArrayList.get(position).getAddress2());
holder.City.setText(altOutletArrayList.get(position).getCity());
holder.Phone.setText(altOutletArrayList.get(position).getPhone());
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.itemClickListener(v, position);
}
});
holder.iButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.imageClickListener(v, position);
}
});
return child;
}
private class Holder {
TextView O_Name;
TextView O_Address1;
TextView O_Address2;
TextView City;
TextView Phone;
Button iButton;
ImageView imageView;
LinearLayout linearLayout;
}
public interface AltOutletClickListener {
void itemClickListener(View v, int position);
void imageClickListener(View v, int position);
}
}
when you add item in java file, use Model
AltOutlet altOutlet = new AltOutlet("test", "address1", "address2", "city", "phone");
altOutlets.add(altOutlet);
AltOutletAdapter altOutletAdapter = new AltOutletAdapter(MainActivity.this, altOutlets, new AltOutletAdapter.AltOutletClickListener() {
#Override
public void itemClickListener(View v, int position) {
// when click layout
}
#Override
public void imageClickListener(View v, int position) {
// when click button
}
});
Is there a way to choose a specific row of my RecyclerView (maybe by getting the index of the row) and then use it to create an intent.
I tried some things by getting the specific row information but that was not even close. My recycler is populated with data from a database.
To choose a specific row of my recycler, you can add setOnItemClickListener code like this one to your onCreate function:
listView_search.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
//Here I'm getting store_id and store_name
TextView store_search_id =(TextView) v.findViewById(R.id.store_search_id);
TextView store_search_name =(TextView) v.findViewById(R.id.store_search_name);
String store_name = store_search_name.getText().toString();
String store_id = store_search_id.getText().toString();
//Then I'm sending theses variables to a shared Intent
Intent myIntent = new Intent(getApplicationContext(), StoresShowActivity.class);
myIntent.putExtra("STORE_ID", store_id);
myIntent.putExtra("STORE_NAME", store_name);
startActivity(myIntent);
}
}
);
You may also want to follow these steps:
A. Add a layout for the Recycle view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_stores_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ksa.ikp.activities.StoresSearchActivity">
<SearchView
android:id="#+id/SearchView_store"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false">
<requestFocus />
</SearchView>
<ListView
android:id="#+id/listView_search"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/SearchView_store" />
</RelativeLayout >
B. Add a layout for the recycleview item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/store_search_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
<TextView
android:id="#+id/store_search_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/store_search_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
C. Use adapter like this one and you can modify it based on your need
public class StoresSearchAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Store> myList = null;
private ArrayList<Store> myArrayList;
public StoresSearchAdapter(Context context, List<Store> myList) {
mContext = context;
this.myList = myList;
inflater = LayoutInflater.from(mContext);
this.myArrayList = new ArrayList<Store>();
this.myArrayList.addAll(myList);
}
public class ViewHolder {
TextView store_search_id;
TextView store_search_name;
TextView store_search_category;
}
#Override
public int getCount() {
return myList.size();
}
#Override
public Store getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.activity_stores_search_item, null);
// Locate the TextViews in activity_stores_search_item.xml
holder.store_search_id = (TextView) view.findViewById(R.id.store_search_id);
holder.store_search_name = (TextView) view.findViewById(R.id.store_search_name);
holder.store_search_category = (TextView) view.findViewById(R.id.store_search_category);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.store_search_id.setText(myList.get(position).getStr_id()+"");
holder.store_search_name.setText(myList.get(position).getStr_name());
String s = SplashActivity.db.getNameById(myList.get(position).getStr_cat_id()+"",SplashActivity.db.TABLE_CATEGORY,SplashActivity.db.COLUMN_CAT_NAME,SplashActivity.db.COLUMN_CAT_ID);
s = " in ("+ s + ")";
holder.store_search_category.setText(s);
return view;
}
// Filter Class
public void filter(String s) {
s = s.toLowerCase(Locale.getDefault());
myList.clear();
if (s.length() == 0) {
myList.addAll(myArrayList);
} else {
myList.addAll(SplashActivity.db.getAllStoresFiltered(s));
}
notifyDataSetChanged();
}
}
Finally your final output will be something like this one:
screenshot
This is my recyclerbackgroundtask
public class RecycleBackgroundTask extends AsyncTask{
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Post> arrayList = new ArrayList<>();
public RecycleBackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
String json_string = "http://192.168.2.110/app/post.php";
#Override
public void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
public Void doInBackground(Void... params) {
try {
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line=bufferedReader.readLine())!=null) {
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Post post = new Post(JO.getString("headline"),JO.getString("source"),JO.getString("url"));
publishProgress(post);
}
Log.d("JSON STRING",json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onProgressUpdate(Post... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
And my RecyclerAdapter
public class RecyclerAdapter extends RecyclerView.Adapter {
private static final int TYPE_HEAD = 0;
private static final int TYPE_LIST = 1;
ArrayList<Post> arrayList = new ArrayList<>();
public RecyclerAdapter (ArrayList<Post> arrayList){
this.arrayList = arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_HEAD){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recycler,parent,false); // instead of row_recycler ,header_layout.
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
if(viewType == TYPE_LIST){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_recycler,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if(holder.viewType == TYPE_LIST) {
Post post = arrayList.get(position-1);
holder.Headline.setText(post.getHeadline());
holder.Source.setText(post.getSource());
//holder.Url.setText(post.getUrl());
}
}
#Override
public int getItemCount() {
return arrayList.size()+1;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView Headline,Source;//,Url;
int viewType;
public RecyclerViewHolder(View view,int viewType){
super(view);
if(viewType == TYPE_LIST) {
Headline = (TextView) view.findViewById(R.id.headline);
Source = (TextView) view.findViewById(R.id.source);
Headline.setOnClickListener(this);
Source.setOnClickListener(this);
// Url = (TextView) view.findViewById(R.id.url);
this.viewType = TYPE_LIST;
}else if (viewType == TYPE_HEAD){
this.viewType = TYPE_HEAD;
}
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemViewType(int position){
if(position==0)
return TYPE_HEAD;
return TYPE_LIST;
}
public void setFilter(ArrayList<Post> newList){
arrayList = new ArrayList<>();
arrayList.addAll(newList);
notifyDataSetChanged();
}
}
Maybe that helps. i already set up a simple onclicklistener with a toast btw
I added ImageButton in CardView in RecyclerView and i made it to add item in favourite (i made sqlite to save favourite ) now i want to make when i open activity that RecyclerView on it show ImageButton with different image if it in Favourite and when pressed on it change image
simply i want to make favourite button (Star image ) like gmail app
RecyclerView Adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<listitem_gib> getDataAdapter;
public RecyclerViewAdapter(List<listitem_gib> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(v,context,getDataAdapter);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
listitem_gib getDataAdapter1 = getDataAdapter.get(position);
holder.name.setText(getDataAdapter1.getName());
holder.num.setText(getDataAdapter1.getnum());
Picasso.with(context).load("http://grassyhat.com/android/image/" + getDataAdapter1.getimg()).into(holder.img1);
holder.fav.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
fav(position);
}
});
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener{
public TextView name;
public TextView num;
public ImageView img1;
ImageButton fav;
Context context;
List<listitem_gib> getDataAdapter;
public ViewHolder(View itemView, Context context ,List<listitem_gib> getDataAdapter ) {
super(itemView);
itemView.setOnClickListener(this);
this.getDataAdapter = getDataAdapter;
this.context = context;
this.fav= (ImageButton) itemView.findViewById(R.id.btn_fav);
name = (TextView) itemView.findViewById(R.id.Main_Text) ;
num = (TextView) itemView.findViewById(R.id.Second_Text) ;
img1 = (ImageView) itemView.findViewById(R.id.img1) ;
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
listitem_gib getDataAdapter =this.getDataAdapter.get(position);
Intent intent = new Intent(this.context,Rewaya_info.class);
intent.putExtra("name",getDataAdapter.getName());
intent.putExtra("url",getDataAdapter.geturl());
intent.putExtra("img",getDataAdapter.getimg());
intent.putExtra("num",getDataAdapter.getnum());
intent.putExtra("size",getDataAdapter.getsize());
this.context.startActivity(intent);
}
}
public void fav(final int position) {
final DB_Sqlit db_sqlit = new DB_Sqlit(context);
final String name = getDataAdapter.get(position).name;
final String img = getDataAdapter.get(position).img;
final String url = getDataAdapter.get(position).url;
final String num = getDataAdapter.get(position).num;
final String size = getDataAdapter.get(position).size;
int count = db_sqlit.get_check_List_Favorite(name);
if (count > 0) {
Toast.makeText(context, "already exist", Toast.LENGTH_SHORT).show();
}else{
Boolean add = db_sqlit.Insert_to_favorite(name, img, url, num, size);
if (add) {
Toast.makeText(context, "added to favourite", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
}
}
}
Database
public class DB_Sqlit extends SQLiteOpenHelper {
public static final String BDname = "mdata.db";
public DB_Sqlit(Context context) {
super(context, BDname, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table favorite ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, img TEXT, url TEXT, num TEXT, size TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS favorite");
onCreate(db);
}
public Boolean Insert_to_favorite(String name, String img, String url, String num, String size) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("img", img);
contentValues.put("url", url);
contentValues.put("num", num);
contentValues.put("size", size);
long result = db.insert("favorite", null, contentValues);
if (result == -1)
return false;
else
return true;
}
public List getAllList_Favorite() {
List<listitem_gib> list = new ArrayList<listitem_gib>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor rs = db.rawQuery("select * from favorite", null);
if (rs.moveToFirst()){
do {
listitem_gib model = new listitem_gib();
model.setId(rs.getString(0));
model.setName(rs.getString(1));
model.seturl(rs.getString(3));
model.setimg(rs.getString(2));
model.setnum(rs.getString(4));
model.setsize(rs.getString(5));
list.add(model);
}while (rs.moveToNext());
}
Log.d("rewayat data", list.toString());
return list;
}
public int get_check_List_Favorite(String Title) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor rs = db.rawQuery("select * from favorite Where name like '"+ Title +"'", null);
rs.moveToFirst();
int count = rs.getCount();
return count;
}
public Integer DeleteFav(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favorite", "id = ?", new String[]{id});
}
CardLayout
<android.support.v7.widget.CardView
android:layout_width="130dp"
android:layout_height="225dp"
app:cardElevation="15dp"
app:cardBackgroundColor="#eae7cb7c"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
app:cardCornerRadius="8dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/img1"
android:layout_width="130dp"
android:layout_height="130dp"
android:layout_gravity="center"
android:scaleType="centerCrop"/>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/delete"
android:layout_gravity="end">
<ImageButton
android:id="#+id/btn_fav"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#android:drawable/btn_star"
android:background="#00ffffff"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"/>
</FrameLayout>
</FrameLayout>
<TextView
android:id="#+id/Main_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label"
android:layout_gravity="right"
android:textSize="15sp"
android:padding="5dp"
android:layout_marginTop="5dp"
android:textColor="#6a9399"/>
<TextView
android:id="#+id/Second_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LongerLabel"
android:layout_gravity="right"
android:textSize="12sp"
android:padding="5dp"
android:textStyle="bold"
android:textColor="#998c6a"/>
</LinearLayout>
</android.support.v7.widget.CardView>
In your onBindViewHolder,, you can just switch the image as needed.
holder.fav.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(holder.fav.getTag() == R.drawable.fav_icon) {
unfav(position);
holder.fav.setImageResource(R.drawable.unfav_icon);
holder.fav.setTag(R.drawable.unfav_icon);
}
else {
fav(position);
holder.fav.setImageResource(R.drawable.fav_icon);
holder.fav.setTag(R.drawable.fav_icon);
}
}
});
In your onBindViewHolder() method, you can add the initial state :
if(holder.fav.getTag() == R.drawable.fav_icon)
holder.fav.setImageResource(R.drawable.fav_icon);
else
holder.fav.setImageResource(R.drawable.unfav_icon);
I am searching for a way to load data into an Expandale List View, the output I want to resemble the one of the picture attached here
In order this to be done dynamically, is it better to be read from a csv? Or to create a DB? Furthermore, on a sub-item press, I want a ScrollView to appear.
Here is the code so far:
The layout of the activity:
<?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="wrap_content">
<ExpandableListView
android:id= "#+id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="#+id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
The itemlayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:id="#+id/grp_child"
android:paddingLeft="50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
And the subitem:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:id="#+id/row_name"
android:paddingLeft="50dp"
android:focusable="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
In the activity, I have hardcoded some values so far, using some tutorials I came across:
public void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photographers);
SimpleExpandableListAdapter expListAdapter =
new SimpleExpandableListAdapter(
this,
createGroupList(),
R.layout.group_row,
new String[] { "Group Item" },
new int[] { R.id.row_name },
createChildList(),
R.layout.child_row,
new String[] {"Sub Item"},
new int[] { R.id.grp_child}
);
setListAdapter( expListAdapter );
}catch(Exception e){
System.out.println("Errrr +++ " + e.getMessage());
}
}
/* Creating the Hashmap for the row */
#SuppressWarnings("unchecked")
private List createGroupList() {
ArrayList result = new ArrayList();
for( int i = 0 ; i < 15 ; ++i ) { // 15 groups........
HashMap m = new HashMap();
m.put( "Group Item","Group Item " + i ); // the key and it's value.
result.add( m );
}
return (List)result;
}
#SuppressWarnings("unchecked")
private List createChildList() {
ArrayList result = new ArrayList();
for( int i = 0 ; i < 15 ; ++i ) { // this -15 is the number of groups(Here it's fifteen)
/* each group need each HashMap-Here for each group we have 3 subgroups */
ArrayList secList = new ArrayList();
for( int n = 0 ; n < 3 ; n++ ) {
HashMap child = new HashMap();
child.put( "Sub Item", "Sub Item " + n );
secList.add( child );
}
result.add( secList );
}
return result;
}
public void onContentChanged () {
System.out.println("onContentChanged");
super.onContentChanged();
}
/* This function is called on each child click */
public boolean onChildClick( ExpandableListView parent, View v, int groupPosition,int childPosition,long id) {
System.out.println("Inside onChildClick at groupPosition = " + groupPosition +" Child clicked at position " + childPosition);
return true;
}
/* This function is called on expansion of the group */
public void onGroupExpand (int groupPosition) {
try{
System.out.println("Group expanding Listener => groupPosition = " + groupPosition);
}catch(Exception e){
System.out.println(" groupPosition Errrr +++ " + e.getMessage());
}
}
I am wondering if it is a good idea to store the data I want to show in separate csv files (one storing the data for the items, one for the subitems. one for the extra information in the ScrollView), to have id-s for identification and to directly read from the CSVs with the OpenCSVReader?
I would appreciate any pieces of advice,
Thanks
create adapter for your expandable listView. like that
public class ExpandableAdapter extends BaseExpandableListAdapter {
private final Context context;
private final List<Menu> parentObjects;
public ExpandableAdapter(Context context, ArrayList<Menu> parentObjects) {
this.context = context;
this.parentObjects = parentObjects;
}
#Override
public int getGroupCount() {
return parentObjects.size();
}
#Override
public int getChildrenCount(int i) {
return parentObjects.get(i).childMenu.size();
}
#Override
public Menu getGroup(int i) {
return parentObjects.get(i);
}
#Override
public Menu.ChildMenu getChild(int i, int i2) {
return parentObjects.get(i).childMenu.get(i2);
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i2) {
return 0;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
Menu currentParent = parentObjects.get(i);
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.navdrawer_parent_item, viewGroup,false);
}
ImageView imageViewIndicator = (ImageView) view.findViewById(R.id.imageViewNav);
if (getChildrenCount(i) == 0)
imageViewIndicator.setVisibility(View.GONE);
else
imageViewIndicator.setVisibility(View.VISIBLE);
TextView textViewNavMenuName = (TextView) view.findViewById(R.id.textViewNavParentMenuName);
ImageView imageViewIcon = (ImageView) view.findViewById(R.id.imageViewIcon);
String base64 = currentParent.getImage();
if (base64 != null && !base64.equals("")) {
byte[] imageAsBytes = Base64.decode(currentParent.getImage().getBytes(), Base64
.DEFAULT);
imageViewIcon.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0,
imageAsBytes.length));
} else
imageViewIcon.setImageResource(R.drawable.ic_action_android);
textViewNavMenuName.setText(currentParent.getMenuName());
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean b, View view,
ViewGroup viewGroup) {
Menu currentChild = getGroup(groupPosition);
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.navdrawer_child_item, viewGroup,false);
}
View divider = view.findViewById(R.id.divider);
if (b)
divider.setVisibility(View.VISIBLE);
else
divider.setVisibility(View.GONE);
TextView textViewNavMenuName = (TextView) view.findViewById(R.id.textViewNavChildMenuName);
textViewNavMenuName.setText(currentChild.childMenu.get(childPosition).getMenuName());
return view;
}
#Override
public boolean isChildSelectable(int i, int i2) {
return true;
}
}
and the model for the expandable listView like
public class Menu {
private int AssociatedApp;
private String MenuName;
private String NavigateURL;
private String ActivityName;
private String Image;
private int MenuID;
public ArrayList<ChildMenu> childMenu;
public ArrayList<ChildMenu> getChildMenu() {
return childMenu;
}
public void setChildMenu(ArrayList<ChildMenu> childMenu) {
this.childMenu = childMenu;
}
public int getAssociatedApp() {
return AssociatedApp;
}
public void setAssociatedApp(int associatedApp) {
AssociatedApp = associatedApp;
}
public String getMenuName() {
return MenuName;
}
public void setMenuName(String menuName) {
MenuName = menuName;
}
public String getNavigateURL() {
return NavigateURL;
}
public void setNavigateURL(String navigateURL) {
NavigateURL = navigateURL;
}
public String getActivityName() {
return ActivityName;
}
public void setActivityName(String activityName) {
ActivityName = activityName;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public Menu() {
}
public int getMenuID() {
return MenuID;
}
public class ChildMenu {
private int AssociatedApp;
private String MenuName;
private String NavigateURL;
private String ActivityName;
private String Image;
private int MenuID;
public ChildMenu(String menuName, String activityName) {
this.MenuName = menuName;
this.ActivityName=activityName;
}
public ChildMenu() {
}
public int getAssociatedApp() {
return AssociatedApp;
}
public void setAssociatedApp(int associatedApp) {
AssociatedApp = associatedApp;
}
public String getMenuName() {
return MenuName;
}
public void setMenuName(String menuName) {
MenuName = menuName;
}
public String getNavigateURL() {
return NavigateURL;
}
public void setNavigateURL(String navigateURL) {
NavigateURL = navigateURL;
}
public String getActivityName() {
return ActivityName;
}
public void setActivityName(String activityName) {
ActivityName = activityName;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public int getMenuID() {
return MenuID;
}
}
}
ok now you can create your menu with data and bindwith expandable listview
elv = (ExpandableListView)findViewById(R.id.elv);
elv.setOnGroupExpandListener(onGroupExpandListenser);
MyExpandableAdapter adapter = new MyExpandableAdapter(this, getData());//where getData() will return list of data.
elv.setAdapter(adapter);
parent 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="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="12dp"
android:paddingLeft="12dp"
android:paddingTop="12dp">
<ImageView
android:contentDescription="#string/app_name"
android:id="#+id/imageViewIcon"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentLeft="true"
android:layout_margin="4dp"
/>
<TextView
android:id="#+id/textViewNavParentMenuName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/imageViewNav"
android:layout_toRightOf="#+id/imageViewIcon"
android:padding="10dp"
android:textSize="15sp"/>
<ImageView
android:contentDescription="#string/app_name"
android:id="#+id/imageViewNav"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="4dp"
android:src="#drawable/ic_action_more_nav"
/>
</RelativeLayout>
<include
layout="#layout/divider"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
child xml
<?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="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/textViewNavChildMenuName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="45dp"
android:gravity="center_vertical"
android:text="TextView"
android:padding="16dp"/>
<include
layout="#layout/divider"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
adding listener for expandable listView like this. groupExpandlistener is used for collasping other groups while open one
private int lastExpandedPosition = -1;
for setting up listener
elv.setOnChildClickListener(new DrawerItemClickListener());
elv.setOnGroupClickListener(new DrawerItemClickListener());
elv.setOnGroupExpandListener(new DrawerItemClickListener());
private class DrawerItemClickListener implements ExpandableListView.OnChildClickListener,
ExpandableListView.OnGroupClickListener, ExpandableListView.OnGroupExpandListener {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int
childPosition, long id) {
selectItem(childPosition, navigationConfig.getBaseExpandableListAdapter
().getChild
(groupPosition, childPosition));
return true;
}
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
selectItem(groupPosition, navigationConfig.getBaseExpandableListAdapter
().getGroup
(groupPosition));
return false;
}
#Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
expandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
}
for sample data use to bind with getData(). note create constructor in model class as given in getData()
//Sample data for expandable list view.
public List<Menu> getData()
{
List<Menu> parentObjects = new ArrayList<Menu>();
for (int i = 0; i<20; i++)
{
parentObjects.add(new Menu("Mother " +i, "Father " +i, "Header " + i, "Footer " +i, getChildren(i)));
}
return parentObjects;
}
private List<Menu.ChildMenu> getChildren(int childCount)
{
List<Menu.ChildMenu> childObjects = new ArrayList<Menu.ChildMenu>();
for (int i =0; i<childCount; i++)
{
childObjects.add(new Menu.ChildMenu("Child " + (i+1), 10 +i ));
}
return childObjects;
}
After i click "more" button, it suppose will extend the listview from 10 to 20.
However after clicked, the list view did not extend and remain original size.
It only can keep the position of scroll bar. This is half of what i need.
newsid = new int[webservice.news.size()];
title = new String[webservice.news.size()];
date = new String[webservice.news.size()];
imagepath = new String[webservice.news.size()];
for (int i = 0; i < webservice.news.size(); i++) {
newsid[i] = webservice.news.get(i).getID();
title[i] = webservice.news.get(i).getNtitle();
date[i] = webservice.news.get(i).getNArticalD();
imagepath[i] = webservice.news.get(i).getImagePath();
}
adapter = new CustomAdapter_ParticularCategoryAllNews(this, title,
date, imagepath);
lv.addFooterView(footermore);
if (constant.isOnline()) {
lv.addFooterView(constant.AdMob());
}
TextView titletext = (TextView) findViewById(R.id.text_pagetitle);
titletext.setText(pagetitletext.toString());
lv.setAdapter(adapter);
This is call when launch activity.
btnmore.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
for (int i = 0; i < webservice.news.size(); i++) {
newsid[i] = webservice.news.get(i).getID();
title[i] = webservice.news.get(i).getNtitle();
date[i] = webservice.news.get(i).getNArticalD();
imagepath[i] = webservice.news.get(i).getImagePath();
}
adapter.setTitle(title);
adapter.setDate(date);
adapter.setImagepath(imagepath);
position = lv.getFirstVisiblePosition();
lv.smoothScrollToPosition(position);
adapter.notifyDataSetChanged();
This is what i call after i click "more button". However the list did not extend from 10 to 20 items.
public class CustomAdapter_ParticularCategoryAllNews extends BaseAdapter {
private Activity activity;
private String[] title, date, imagepath;
private static LayoutInflater inflater = null;
private ImageLoader_Loader imageLoader;
private WindowManager wm = null;
private Display display;
private Config_ConstantVariable constant;
public CustomAdapter_ParticularCategoryAllNews(Activity a, String[] title,
String[] date, String[] imagepath) {
activity = a;
this.title = title;
this.date = date;
this.imagepath = imagepath;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
imageLoader = new ImageLoader_Loader(activity.getApplicationContext());
constant = new Config_ConstantVariable(activity);
}
public int getCount() {
return title.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setTitle(String[] title) {
this.title = title;
}
public void setDate(String[] date) {
this.date = date;
}
public void setImagepath(String[] imagepath) {
this.imagepath = imagepath;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.main_particularcategoryallnewslist,
parent, false);
LinearLayout linear = (LinearLayout) vi.findViewById(R.id.layout_image);
ImageView imageview = (ImageView) vi
.findViewById(R.id.image_categoryallnewstitle);
TextView titletext = (TextView) vi
.findViewById(R.id.text_categoryallnewstitle);
TextView datetext = (TextView) vi.findViewById(R.id.text_newsdate);
if (!imagepath[position].toString().equals("no picture")) {
imageview.setVisibility(View.VISIBLE);
linear.setVisibility(View.VISIBLE);
imageLoader.DisplayImage(imagepath[position], imageview);
} else {
imageview.setVisibility(View.GONE);
imageview.setImageDrawable(null);
linear.setVisibility(View.GONE);
display = wm.getDefaultDisplay();
int screenWidth = display.getWidth();
titletext.setWidth(screenWidth);
}
if (constant.getscreenresolution() >= 800 && constant.ScreenOrientation() == 1) {
titletext.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30);
datetext.setTextSize(TypedValue.COMPLEX_UNIT_PX, 20);
}
titletext.setText(title[position].toString());
datetext.setText(date[position].toString());
return vi;
}
}
This is the CustomAdapter class.
In your adapter add:
public void setTitle(String[] title) {
this.title = title;
}
public void setDate(String[] date) {
this.date = date;
}
public void setImagepath(String[] imagepath) {
this.imagepath = imagepath;
}
When the more button is pressed call the three methods above with arrays containing 20 objects. Then call notifyDataSetChanged on your adapter.
Update:
This is working for me:
Activity:
public class HelpProjectActivity extends Activity {
private ArrayList<Item> items;
private boolean extend = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createArray();
ListView lv = (ListView)findViewById(R.id.list);
lv.setAdapter(new HelpListAdapter());
}
private void createArray() {
items = new ArrayList<Item>();
for(int i = 0; i < 20; i++) {
Item item = new Item();
item.title = "Title " + i;
item.subtitle = "Subtitle " + i;
item.image = "default";
items.add(item);
}
}
public void morePressed(View v) {
extend = !extend;
Button b = (Button) findViewById(R.id.button);
b.setText(extend ? R.string.less_button : R.string.more_button);
ListView lv = (ListView)findViewById(R.id.list);
((BaseAdapter)lv.getAdapter()).notifyDataSetChanged();
}
private class HelpListAdapter extends BaseAdapter {
#Override
public int getCount() {
if (extend) {
return items.size();
}
return items.size()/2;
}
#Override
public Object getItem(int pos) {
return items.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = View.inflate(getApplicationContext(), R.layout.litst_item, null);
}
Item item = items.get(pos);
TextView titleText = (TextView) v.findViewById(R.id.list_item_title);
titleText.setText(item.title);
TextView subtitleText = (TextView) v.findViewById(R.id.list_item_subtitle);
subtitleText.setText(item.subtitle);
ImageView image = (ImageView) v.findViewById(R.id.list_image);
if (item.image.equalsIgnoreCase("default")) {
image.setImageResource(R.drawable.default_list_image);
} else {
// what ever
}
return v;
}
}
}
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" >
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
android:onClick="morePressed"
android:text="#string/more_button" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
list_item.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="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="#+id/list_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:layout_gravity="center_vertical"
android:contentDescription="#string/list_image" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:id="#+id/list_item_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/list_item_subtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="italic" />
</LinearLayout>
</LinearLayout>
Item.java:
public class Item {
String image;
String title;
String subtitle;
}
adapter.notifyDataSetChanged(); try this