Hi all i have problemm that getView() is not called. Sup please. And in project i am using ViewPager. So maybe it's becouse of that
Here my MainActivity
package com.uinleader.animewatcher;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private List<View> pages;
private View recent;
private View top_seven;
private ViewPager mPager;
private final ArrayList<Parsed> info = new ArrayList<Parsed>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUi();
LVInit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(android.R.menu.main, menu);
return true;
}
private void initUi() {
LayoutInflater inflater = LayoutInflater.from(this);
pages = new ArrayList<View>();
recent = inflater.inflate(R.layout.recent, null);
recent.setTag(getString(R.string.recent));
top_seven = inflater.inflate(R.layout.top_seven, null);
top_seven.setTag(getString(R.string.top));
pages.add(recent);
pages.add(top_seven);
PAdapter adapter = new PAdapter(pages);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(adapter);
mPager.setCurrentItem(0);
}
private void LVInit() {
LayoutInflater inflater = LayoutInflater.from(this);
Parsed one = new Parsed("One", "1", R.drawable.ic_launcher);
Parsed two = new Parsed("Two", "2", R.drawable.ic_launcher);
Parsed three = new Parsed("Three", "3", R.drawable.ic_launcher);
View v = inflater.inflate(R.layout.top_seven, null);
info.add(one);
info.add(two);
info.add(three);
ListView lv = (ListView) v.findViewById(R.id.listView1);
MArrayAdapter radapter = new MArrayAdapter(MainActivity.this, R.id.listView1, info);
lv.setAdapter(radapter);
}
}
Here is adapter
package com.uinleader.animewatcher;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by uinleader on 28.09.13.
*/
public class MArrayAdapter extends ArrayAdapter<Parsed> {
private final Activity activity;
private final ArrayList<Parsed> items;
public MArrayAdapter(Activity a, int textViewResourceId, ArrayList<Parsed> items) {
super(a, textViewResourceId, items);
activity = a;
this.items = items;
Log.e("ListViewDebug", "Inside Adapter");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.e("ListViewDebug", "Start Function");
View view = convertView;
ViewHolder holder;
if (view == null) {
Log.e("ListViewDebug", "In First IF");
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_layout, parent, false);
holder = new ViewHolder();
holder.title = (TextView) view.findViewById(R.id.anime_title);
holder.ep_num = (TextView) view.findViewById(R.id.ep_number);
holder.ep_preview = (ImageView) view.findViewById(R.id.ep_preview);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
Parsed item = items.get(position);
if(item!=null) {
holder.title.setText(item.anime_title);
holder.ep_num.setText("Episode: "+item.ep_num);
holder.ep_preview.setImageResource(item.img);
}
return view;
}
#Override
public int getCount() {
return items.size();
}
private static class ViewHolder {
public TextView title;
public TextView ep_num;
public ImageView ep_preview;
}
}
Here is my class for data. And XML's
package com.uinleader.animewatcher;
/**
* Created by uinleader on 28.09.13.
*/
public class Parsed {
public String anime_title;
public String ep_num;
public int img;
public Parsed (String anime_title, String ep_num, int img ){
this.anime_title = anime_title;
this.ep_num = ep_num;
this.img = img;
}
}
XML for list.
<?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" >
<ListView
android:id="#+id/listView1"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</ListView>
</LinearLayout>
XML for row's
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
>
<ImageView
android:layout_width="200px"
android:layout_height="200px"
android:id="#+id/ep_preview"
android:layout_column="0"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/anime_title"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/ep_preview" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ep_number"
android:layout_below="#+id/anime_title"
android:layout_toRightOf="#+id/ep_preview" />
</RelativeLayout>
The setContentView(R.layout.activity_main); already "inflates" the current layout the activity is using..i don't why you are inflating other stuff in the "init" methods, that is probably why nothing is being called because the activity remains displaying the view set on R.layout.activity_main.
ArrayAdapter works a bit differently than BaseAdapter - which is for what you're implementing your getView
I suggest several options to fix :
change your ArrayAdapter to BaseAdapter
or use the built in ArrayList that comes with the ArrayList adapter
in your constructor write the following :
public MArrayAdapter(Activity a, int textViewResourceId, ArrayList<Parsed> items) {
super(a, textViewResourceId, items); //<== call to super instantiates the items
activity = a;
//ArrayListAdapter has a built in arrayList - use it
Log.e("ListViewDebug", "Inside Adapter");
}
change your getView to this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.e("ListViewDebug", "Start Function");
View view = convertView; // **note why do you allocate again? just write convertview everywhere instead of view**
ViewHolder holder;
if (view == null) {
Log.e("ListViewDebug", "In First IF");
//**I recommend instantiating the inflater once inside the constructor**
LayoutInflater inflater =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_layout, parent, false);
holder = new ViewHolder();
holder.title = (TextView) view.findViewById(R.id.anime_title);
holder.ep_num = (TextView) view.findViewById(R.id.ep_number);
holder.ep_preview = (ImageView) view.findViewById(R.id.ep_preview);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
Parsed item = (Parsed)getItem(position); //<==== this
if(item!=null) {
holder.title.setText(item.anime_title);
holder.ep_num.setText("Episode: "+item.ep_num);
holder.ep_preview.setImageResource(item.img);
}
return
view;
}
Related
We are developing an Android application which creates plans and schedules. I have an ExpandableListView and I need to add deleting buttons where the user can delete a specific schedule or the complete plan. The Schedule item is the Child of the Plan item.
I was developing deleting the schedule part first. I thought that each child item can include one text view and the deleting button. This is the schedule_group.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="2">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.8">
<TextView
android:id="#+id/scheduleGroup"
android:layout_width="355dp"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textColor="#android:color/black" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.2">
<ImageButton
android:id="#+id/scheduleDeleteBtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:srcCompat="#drawable/delete_icon"
android:clickable="true"
></ImageButton>
</LinearLayout>
</LinearLayout>
And here is the PlansFragment.java where I create and delete the plans and the schedules.
package com.example.easyplan;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class PlansFragment extends Fragment {
MainAdapter mainAdapter;
ExpandableListView planExplandable;
List<String> listPlanName;
HashMap<String, List<String>> listSchedules;
ImageButton scheduleDeleteBtn;
TextView textView;
static int count = 0;
View view;
public PlansFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_plans_fragment, container, false);
listPlanName = new ArrayList<String>();
listSchedules = new HashMap<String, List<String>>();
scheduleDeleteBtn = view.findViewById(R.id.scheduleDeleteBtn);
scheduleDeleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteSchedule();
}
});
// get the listview
planExplandable = (ExpandableListView) view.findViewById(R.id.plansExpandable);
textView = view.findViewById(R.id.scheduleGroup);
createAPlan(3);
createAPlan(1);
createAPlan(3);
createAPlan(4);
mainAdapter = new MainAdapter(getActivity(), listPlanName, listSchedules);
// setting list adapter
planExplandable.setAdapter(mainAdapter);
return view;
}
The problem is here:
private void deleteSchedule() {
}
private void createAPlan(int sch){
listPlanName.add("Plan#"+(count+1));
List<String> schedules = new ArrayList<String>();
if(sch > 0 ){
for (int i = 1; i <= sch; i++){
schedules.add("Schedule#" + i);
}
}
listSchedules.put(listPlanName.get(count),schedules);
count++;
}
}
I'm not sure how to access the child item via the button. If you could help that would be great! Thank you.
I added the remove part under getChildView() method. If anyone needs a similar solution:
package com.example.easyplan;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class MainAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> listPlan; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> listScheduleMap;
ImageButton scheduleDeleteBtn;
public MainAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this.listPlan = listDataHeader;
this.listScheduleMap = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this.listScheduleMap.get(this.listPlan.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.schedule_group, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.scheduleGroup);
scheduleDeleteBtn = convertView.findViewById(R.id.scheduleDeleteBtn);
scheduleDeleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<String> plan = listScheduleMap.get(listPlan.get(groupPosition));
plan.remove(childPosition);
notifyDataSetChanged();
}
});
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this.listScheduleMap.get(this.listPlan.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this.listPlan.get(groupPosition);
}
#Override
public int getGroupCount() {
return this.listPlan.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.plan_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.planGroup);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
i have tried several methods to make my items clickable i have read about focus and added the lines in my XML file Relative layout. nothing seems to help. the click listener still doesn't seem to do anything for me.. please help!!!
this is my activity list view class:
package com.example.trezah12.adminmodule;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class AdminList extends AppCompatActivity {
CustomAdapterAdmin adapterAdmin;
ArrayList<Admin> list;
ListView list1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_list);
DBhandler dBhandler = new DBhandler(this);
list = new ArrayList<>();
list1 = (ListView) findViewById(R.id.listview4);
viewData();
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long Id) {
Intent intent = new Intent(AdminList.this, LaunchActivity.class);
}
});
}
private void viewData() {
final DBhandler dbHandler3 = new DBhandler(AdminList.this);
Cursor cursor = dbHandler3.viewData();
if (cursor.getCount() == 0){
Toast toast = Toast.makeText(getApplicationContext(), "Sorry no Data Found!!", Toast.LENGTH_SHORT);
}
else {
while (cursor.moveToNext()) {
Admin admin = new Admin();
admin.setUsername(cursor.getString(0));
list.add(admin);
list1 = (ListView) findViewById(R.id.listview4);
adapterAdmin = new CustomAdapterAdmin(list, AdminList.this);
list1.setAdapter(adapterAdmin);
}
}
}
}
below is my custom adapter class for admin:
package com.example.trezah12.adminmodule;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by trezah12 on 23/10/2018.
*/
public class CustomAdapterAdmin extends BaseAdapter {
private List<Admin> adminList = new ArrayList<Admin>();
private Context activity;
private static LayoutInflater inflater = null;
public CustomAdapterAdmin(List<Admin> adminList, Context activity) {
this.adminList = adminList;
this.activity = activity;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return adminList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (convertView == null) {
v = inflater.inflate(R.layout.customeadmin, null);
}
Admin admin = adminList.get(position);
TextView txt1 = (TextView) v.findViewById(R.id.textView1);
txt1.setText(admin.getUsername());
TextView txt2 = (TextView) v.findViewById(R.id.textView2);
txt2.setText(admin.getPassword());
return v;
}
}
Below is my XML file for list view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="#+id/listview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</ListView>
</RelativeLayout>
that is because yout did not start the activity
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long Id) {
Intent intent = new Intent(AdminList.this, LaunchActivity.class);
startActivity(intent);
}
});
I'm trying to follow this guide on creating a ListView with two different layouts to create an activity for a settings menu but some parts are ambiguous to me and my attempts aren't working.
http://android.amberfog.com/?p=296
activity_settings.xml
<?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="com.example.austin.kanadrill.SettingsActivity">
<ListView
android:id="#+id/settingsListView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
SettingsActivity.java
package com.example.austin.kanadrill;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
ListView settingsListView = findViewById(R.id.settingsListView);
SettingsAdapter settingsAdapter = new SettingsAdapter();
settingsAdapter.addItem("Hiragana");
settingsAdapter.addItem("Katakana");
settingsAdapter.addItem("Fonts");
settingsAdapter.addCheckBoxItem("Speed Mode");
settingsListView.setAdapter(settingsAdapter);
}
}
SettingsAdapter.java
package com.example.austin.kanadrill;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.TreeSet;
public class SettingsAdapter extends BaseAdapter {
final int TYPE_ITEM = 0;
final int TYPE_CHECKBOX_ITEM = 1;
final int TYPE_MAX_COUNT = 2;
Context ctx;
ArrayList mData = new ArrayList();
LayoutInflater mInflator;
TreeSet mCheckBoxSet = new TreeSet();
public SettingsAdapter() {
mInflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addCheckBoxItem(final String item) {
mData.add(item);
mCheckBoxSet.add(mData.size()-1);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return mCheckBoxSet.contains(position) ? TYPE_CHECKBOX_ITEM : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return (String) mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if(convertView == null) {
holder = new ViewHolder();
switch(type) {
case TYPE_ITEM:
convertView = mInflator.inflate(android.R.layout.simple_list_item_1, null);
holder.textView = (TextView) convertView.findViewById(R.id.settingsListView);
break;
case TYPE_CHECKBOX_ITEM:
convertView = mInflator.inflate(android.R.layout.simple_list_item_multiple_choice, null);
holder.textView = (TextView) convertView.findViewById(R.id.settingsListView);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText((String)mData.get(position));
return convertView;
}
private static class ViewHolder {
public TextView textView;
}
}
I faced issues especially in the constructor for SettingsAdapter because I think I needed to create a context to call getSystemService() and I doubt I did that properly. I also did not understand exactly what to do in getView() so that is likely wrong too. My goal is to just have a ListView where the first three Strings are simple_list_item_1 and a fourth string is simple_list_item_multiple_choice. How can I fix this code to accomplish that, or just start from scratch?
Thank you.
There are 2 issues in your code
Pass the Activity context to Settings Apdapter, It must be throwing exception.
SettingsActivity.java
SettingsAdapter settingsAdapter = new SettingsAdapter(this);
SettingsAdpater.java
public SettingsAdapter(Context context) {
ctx = context
mInflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
and for textview id, use android.R.id.text1 (that's the id defined in R.layout.simple_list_item_1 and android.R.layout.simple_list_item_multiple_choice)
switch(type) {
case TYPE_ITEM:
convertView = mInflator.inflate(android.R.layout.simple_list_item_1, null);
holder.textView = (TextView) convertView.findViewById(android.R.id.text1);
break;
case TYPE_CHECKBOX_ITEM:
convertView = mInflator.inflate(android.R.layout.simple_list_item_multiple_choice, null);
holder.textView = (TextView) convertView.findViewById(android.R.id.text1);
break;
}
Let me know if you didn't understand any part, happy to help.
I have a RecyclerView that gets inflated in a Fragment. The problem is, when the items count gets more than views height, every item that is in the view will get a width of highest content (I mean all will get wrap content of highest width). In the image it's more specific, also after scrolling those views that will get refreshed will have a correct width (match parent). I already have tried those code suggestions on other questions but still problem exists. here is my code:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.complex_item, parent, false);
return new ViewHolder(itemView);
}
The xml layout for items:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
android:layout_margin="5dp"
android:id="#+id/baseBg"
android:orientation="vertical">
<LinearLayout
android:id="#+id/expand_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_item_background"
android:foreground="?selectableItemBackground"
android:gravity="center|right"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/textViewTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textColor="#color/colorPage5"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
Code snippet that does the fragment replace:
mainPageFrameLayout.removeAllViews();
FragmentTransaction ft =
getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainPageFrameLayout, new MojtamaFragment(id, "3"));
ft.commit();
And the mainPageFrameLayout:
<FrameLayout
android:id="#+id/mainPageFrameLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:animateLayoutChanges="true"
android:background="#color/colorPage5" />
The adapter and the onCreateView:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recycler_view_fragment, container, false);
final RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
...
//(this part items is getting generated by a Http Request)
...
recyclerView.setAdapter(new SimpleAdapter(recyclerView, id, title, getActivity(), complexID,MojtamaFragment.this));
return rootView;
}
Images:
Edit: Image explanation: as you can see in image 1 when items numbers gets more than views height items width gets wrap_content instead of match_parent (Image 2 is the correct one that it should be) in image 3 as you can see after i did scroll, items that get's re-instantiated gets correct width. I hope you get the point.
Edit 3: This is whole adapter and viewholder code and imports:
package com.ahrabi.ojekavir.Fragments;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.ahrabi.ojekavir.R;
import com.ahrabi.ojekavir.connector.HttpVolley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Ahrabi2 on 1/10/2018.
*/
#SuppressLint("ValidFragment")
public class MojtamaFragment extends Fragment {
public static final String GET_COMPLEX_LIST_URL = "/Building/getComplexList";
public static final String LOGIN_URL = "/user/Login";
SharedPreferences prefs;
public String firsturl;
private String[] id, title;
private String idCame, complexID;
#SuppressLint("ValidFragment")
public MojtamaFragment(String id, String complexID) {
this.idCame = id;
this.complexID = complexID;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recycler_view_fragment, container, false);
final RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (prefs.getBoolean("net_switch", false)) {
// Your switch is on
Log.v("Requests", "Over Network");
firsturl = prefs.getString("internet_url", getResources().getString(R.string.pref_default_display_internet));
Log.v("Over internet url", firsturl);
} else {
// Your switch is off
Log.v("Requests", "Over Local");
firsturl = prefs.getString("local_url", getResources().getString(R.string.pref_default_display_local));
Log.v("Local url", firsturl);
}
String[] keys = new String[2];
String[] values = new String[2];
keys[0] = "ComplexTypeId";
keys[1] = "regionID";
values[0] = complexID;
values[1] = idCame;
new HttpVolley
().HttpVolleyPost(getActivity(), firsturl + GET_COMPLEX_LIST_URL, keys, values, new HttpVolley.VolleyResponseListener() {
#Override
public void onError(String message) {
}
#Override
public void onResponse(String response) {
if (response.contentEquals("-7")) {
} else {
// response = response.replaceAll("\\", "");
Log.v("Response", response);
String jsonResult = "{" + "\"" + "android" + "\"" + ":" + response
+ "}";
try {
JSONObject jObject = new JSONObject(jsonResult);
// Getting JSON Array from URL
JSONArray android = jObject.getJSONArray("android");
Log.v("android", android.toString());
Log.v("android.length()", "" + android.length());
id = new String[android.length()];
title = new String[android.length()];
for (int i = 0; i < android.length(); i++) {
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
id[i] = c.getString("id");
title[i] = c.getString("Name");
}
recyclerView.setAdapter(new SimpleAdapter(recyclerView, id, title, getActivity(), complexID,MojtamaFragment.this));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
return rootView;
}
private void showLoginPopup(String page) {
LayoutInflater curInflate = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View curLayout = curInflate.inflate(R.layout.login_popup,
(ViewGroup) getActivity().findViewById(R.id.mainLinearPopup));
final PopupWindow swindo = new PopupWindow(curLayout,
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
swindo.setBackgroundDrawable(new BitmapDrawable());
swindo.setFocusable(true);
// swindo.setAnimationStyle(R.style.PopupWindowAnimation);
swindo.showAtLocation(curLayout, Gravity.BOTTOM,
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
LinearLayout bg = (LinearLayout) curLayout
.findViewById(R.id.bgLinearPopup);
LinearLayout loginIV = (LinearLayout) curLayout
.findViewById(R.id.loginIV);
final EditText loginUserName = (EditText) curLayout
.findViewById(R.id.loginUserName);
final EditText loginPassword = (EditText) curLayout
.findViewById(R.id.loginPassword);
if (page.contentEquals("1"))
loginIV.setBackgroundResource(R.drawable.item_brown_bg);
else if (page.contentEquals("3"))
loginIV.setBackgroundResource(R.drawable.item_orange_bg);
bg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
swindo.dismiss();
}
});
loginIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (loginUserName.getText().toString().contentEquals("")){
} else if (loginPassword.getText().toString().contentEquals("")){
} else {
String[] keys = new String[2];
String[] values = new String[2];
keys[0] = "userName";
keys[1] = "password";
values[0] = loginUserName.getText().toString();
values[1] = loginPassword.getText().toString();
new HttpVolley
().HttpVolleyPost(getActivity(), firsturl + LOGIN_URL, keys, values, new HttpVolley.VolleyResponseListener() {
#Override
public void onError(String message) {
}
#Override
public void onResponse(String response) {
if (response.contentEquals("1")) {
} else {
}
}
});
}
}
});
}
private static class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ViewHolder> {
private RecyclerView recyclerView;
private String[] id, title;
private Context context;
private String complexID;
private MojtamaFragment mojtamaFragment;
public SimpleAdapter(RecyclerView recyclerView, String[] id, String[] title, Context context, String complexID,MojtamaFragment mojtamaFragment) {
this.recyclerView = recyclerView;
this.id = id;
this.title = title;
this.context = context;
this.complexID = complexID;
this.mojtamaFragment = mojtamaFragment;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.complex_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textViewTitle.setText(title[position]);
if (complexID.contentEquals("1"))
holder.textViewTitle.setTextColor(context.getResources().getColor(R.color.colorPage6));
else if (complexID.contentEquals("3"))
holder.textViewTitle.setTextColor(context.getResources().getColor(R.color.colorPage5));
}
#Override
public int getItemCount() {
return id.length;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewTitle;
private LinearLayout expandButton;
public ViewHolder(View itemView) {
super(itemView);
expandButton = itemView.findViewById(R.id.expand_button);
textViewTitle = itemView.findViewById(R.id.textViewTitle);
expandButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) recyclerView.findViewHolderForAdapterPosition(getAdapterPosition());
mojtamaFragment.showLoginPopup(complexID);
}
}
}
}
After so much editing and experiencing i found a part of code from my xml layout (the one that FrameLayout is in it and fragment gets replaced by it) has something to do with error:
<android.support.constraint.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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.ahrabi.ojekavir.CityActivity"
tools:showIn="#layout/activity_city">
after removing app:layout_behavior and changing ContraintLayout to some Linear or RelativeLayout problem now is gone.
I don't know why this part raises such problem, but it has definitely a reason.
I am encountering errors when trying to use the constructor of my arrayAdapter for a listView. When I call it like this:
ListArrayAdapter adapters = new ListArrayAdapter(this, R.layout.list_view_row_item, foodList);
I get the error (in eclipse):
the constructor ListArrayAdapter(Context, int, ArrayList<ListItem>) is undefined.
This is the code for the arrayAdapter:
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.LauncherActivity.ListItem;
import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ListArrayAdapter extends ArrayAdapter<ListItem> {
Context mContext;
int layoutResourceId;
ListItem data[] = null;
private ProgressBar progressBar;
private int progressStatus = 0;
private TextView textView;
private Handler handler = new Handler();
ArrayList<ListItem> foodList = new ArrayList<ListItem>();
public ListArrayAdapter(Context mContext, int layoutResourceId, ArrayList<ListItem> foodList) {
super(mContext, layoutResourceId, foodList);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.foodList = foodList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
// inflate the layout
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
}
return convertView;
}
The main part of my program:
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.app.fridgelist.*;
public class MainScreen extends Activity {
private static Calendar d = Calendar.getInstance();
private static Date kurrentTime = d.getTime();
public int listItems;
public static Context mainScreen;
public ArrayList<ListItem> foodList = new ArrayList<ListItem>();
private static ListItem newFood1 = new ListItem(0, "Pasta", 99, (int) (kurrentTime.getTime()));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
if (savedInstanceState == null) {
//getFragmentManager().beginTransaction()
//.add(R.id.container, new PlaceholderFragment())
//.commit();
}
mainScreen = this;
foodList.add(newFood1);
listItems = 1;
ListArrayAdapter adapters = new ListArrayAdapter(getBaseContext(), R.layout.list_view_row_item, foodList);
ListView yourListView = (ListView) findViewById(R.id.listOne);
//yourListView.setAdapter(adapters);
//yourListView.setOnItemClickListener(new OnItemClickListener() {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_screen, container, false);
return rootView;
}
}
}
// try this way,hope this will help you...
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/lstFood"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="#+id/txtFood"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private ListView lstFood;
ArrayList<HashMap<String,String>> foodList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstFood = (ListView) findViewById(R.id.lstFood);
foodList = new ArrayList<HashMap<String, String>>();
HashMap<String,String> food1 = new HashMap<String,String>();
food1.put("id","1");
food1.put("name","pasta");
food1.put("prize","99");
food1.put("time",String.valueOf(Calendar.getInstance().getTime()));
HashMap<String,String> food2 = new HashMap<String,String>();
food2.put("id","2");
food2.put("name","pizza");
food2.put("prize","199");
food2.put("time",String.valueOf(Calendar.getInstance().getTime()));
foodList.add(food1);
foodList.add(food2);
CustomAdapter adapters = new CustomAdapter(this,foodList);
lstFood.setAdapter(adapters);
lstFood.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String,String> food = foodList.get(position);
System.out.println("Food Id : "+food.get("id"));
System.out.println("Food Name : "+food.get("name"));
System.out.println("Food Prize : "+food.get("prize"));
System.out.println("Food Time : "+food.get("time"));
}
});
}
class CustomAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<HashMap<String,String>> foodList;
public CustomAdapter(Context mContext,ArrayList<HashMap<String,String>> foodList) {
this.mContext = mContext;
this.foodList = foodList;
}
#Override
public Object getItem(int position) {
return foodList.get(position);
}
#Override
public int getCount() {
return foodList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
holder.txtFood = (TextView) convertView.findViewById(R.id.txtFood);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtFood.setText(foodList.get(position).get("name"));
return convertView;
}
class ViewHolder{
TextView txtFood;
}
}
}
Change here from
ListArrayAdapter adapters = new ListArrayAdapter(getBaseContext(), R.layout.list_view_row_item, foodList);
to
ListArrayAdapter adapters = new ListArrayAdapter(YourActivityName.this, R.layout.list_view_row_item, foodList);
yourListView.setAdapter(adapters);