Progress bar in listview - android

I have sqlite database that have table(benefits) and designed like this
recipe percent name ID
1 100 Digestion 1
1 80 Lower ch 2
1 60 Immune sys 3
I want to create list that have two item.
first is name that i have no problem with
second is percent that i want to show like progress bar.
this is what i wrote to do this.
public class BenefitsFragment extends Fragment {
private JuiceDatabase db;
public String data;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_benefits, container, false);
db = new JuiceDatabase(super.getActivity());
//Ingredients Code
Cursor benefits = db.getbenefitsresult();
String[] from = new String[]
{"name","percent"};
int[] to = new int[]
{R.id.input,R.id.progressbar};
final SimpleCursorAdapter myadapter = new CustomSimpleCursorAdapter(
super.getActivity(),
R.layout.ingredients,
benefits,
from,
to);
final ListView list1 = (ListView) rootView.findViewById(R.id.list1);
list1.setAdapter(myadapter);
list1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (calculateHeight(list1))));
return rootView ;
}
private int calculateHeight(ListView list) {
int height = 0;
for (int i = 0; i < list.getCount(); i++) {
View childView = list.getAdapter().getView(i, null, list);
childView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
height+= childView.getMeasuredHeight();
}
//dividers height
height += list.getDividerHeight() * (list.getCount()+5);
return height;
}
}
fragment_benefits.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:scrollbars="none">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/group"
android:layout_marginRight="15sp"
android:layout_marginLeft="15sp"
android:layout_marginTop="15sp"
android:layout_marginBottom="15sp"
android:elevation="15dp">
<TextView
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="5sp"
android:paddingLeft="5sp"
android:paddingTop="5sp"
android:paddingBottom="10sp"
android:text="benefits"
android:textSize="22sp"
android:textColor="#color/dark_grey"
android:gravity="center_horizontal" />
<View style="#style/divider1"/>
<ListView
android:id="#+id/list1"
android:layout_width="fill_parent"
android:layout_height="0sp"
android:scrollbars="none"
android:paddingTop="5sp"
android:paddingLeft="5sp"
android:paddingRight="5sp"
android:layout_marginBottom="5sp"
android:layout_weight="1"
android:clickable="false">
</ListView>
</LinearLayout>
</LinearLayout>
ingredients.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true">
<TextView
android:id="#+id/input"
android:layout_width="fill_parent"
android:layout_height="#dimen/list_name_height"
android:layout_alignWithParentIfMissing="true"
android:textSize="12sp"
android:textColor="#color/dark_grey"
android:gravity="center_vertical|center"
android:background="#android:color/transparent"
android:elevation="8sp"
android:elegantTextHeight="false"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="fill_parent"
android:layout_height="20sp"
android:layout_below="#+id/input"
android:textSize="25sp"
android:longClickable="false"
style="#android:style/Widget.ProgressBar.Horizontal">
</ProgressBar>
CustomSimpleCursorAdabtor.class
public class CustomSimpleCursorAdapter extends SimpleCursorAdapter {
public CustomSimpleCursorAdapter(Context context, int layout, Cursor c, String[] from,
int[] to) {
super(context, layout, c, from, to);
}
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
updateProgressbar(view, cursor);
}
private void updateProgressbar(View view, Cursor cursor) {
ProgressBar progressBar = (ProgressBar) view
.findViewById(R.id.progressbar);
progressBar.setMax(100);
progressBar.setProgress(cursor.getInt(cursor
.getColumnIndex("percent")));
}
}
CursorAdaptor
public Cursor getbenefitsresult(){
SQLiteDatabase db = this.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String data=StoreData.data;
String sqlTables = "benefits";
qb.setTables(sqlTables);
Cursor c = db.rawQuery("SELECT 0 _id, name, percent FROM benefits WHERE recipe ="+data,null);
c.moveToFirst();
Log.d("percent",Integer.toString(c.getInt(c
.getColumnIndex("percent"))));
db.close();
return c;
}
After run the program when i click this fragment tab it go back to previous page!!!
whats the problem ?
sorry if its noobish question this is my first app.
EDIT 1:
public class MainRecipe extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "مواد لازم", "ارزش غذایی", "فواید" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_recipe);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}

I found thee problem myself.
that was in CustomSimpleCursorAdapter
I must used setProgressbar instead of updateprogressbar .

Related

ViewPager Text Onclick

I am currently doing this android tutorial https://www.androidhive.info/2016/05/android-build-intro-slider-app/ .
I want to implement the onClick() event inside the viewpager page like if I clicked the text, it will direct me to another page.
Is it possible? If possible, please help me? Thanks
here is my code for viewPager.
public class welcomeActivity extends AppCompatActivity {
ViewPager viewPager;
private LinearLayout myLinear;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private MyViewPagerAdapter myViewPagerAdapter;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().
setSystemUiVisibility
(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);}
setContentView(R.layout.activity_welcome);
viewPager = (ViewPager) findViewById(R.id.view_pager);
myLinear = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
layouts = new int[]{
R.layout.slide1, R.layout.slide2, R.layout.slide3, R.layout.slide4, R.layout.slide5
};
addBottomDots(0);
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int current = getItem(+1);
if (current < layouts.length){
viewPager.setCurrentItem(current);
}else launchHomeScreen();
}
});
}
ViewPager.OnPageChangeListener viewPagerListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
addBottomDots(position);
if (position == layouts.length -1){
btnSkip.setVisibility(View.GONE);
btnNext.setText("Get Started..");
}
else {
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
myLinear.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
myLinear.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
//prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(welcomeActivity.this, MainActivity.class));
finish();
}
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
public class MyViewPagerAdapter extends PagerAdapter{
private LayoutInflater inflater;
#Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(layouts[position],container,false);
container.addView(v);
return v;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
Here is my layouts. (activity_welcome.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:showIn="#layout/activity_welcome">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/layoutDots"
android:layout_width="match_parent"
android:layout_height="#dimen/dots_height"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/dots_margin_bottom"
android:gravity="center"
android:orientation="horizontal"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:alpha=".5"
android:layout_above="#id/layoutDots"
android:background="#android:color/white" />
<Button
android:id="#+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#null"
android:text="Next"
android:textColor="#android:color/white" />
<Button
android:id="#+id/btn_skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#null"
android:text="BACK"
android:textColor="#android:color/white" />
</RelativeLayout>
slide1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_screen1">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:layout_width="#dimen/img_width_height"
android:layout_height="#dimen/img_width_height"
android:src="#drawable/ic_food" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/slide_1_title"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_title"
android:textStyle="bold" />
<TextView
android:id="#+id/tvFood"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:paddingLeft="#dimen/desc_padding"
android:paddingRight="#dimen/desc_padding"
android:text="#string/slide_1_desc"
android:textAlignment="center"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_desc" />
</LinearLayout>
</RelativeLayout>
slide2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_screen2">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:layout_width="#dimen/img_width_height"
android:layout_height="#dimen/img_width_height"
android:src="#drawable/ic_movie" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/slide_2_title"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_title"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:paddingLeft="#dimen/desc_padding"
android:paddingRight="#dimen/desc_padding"
android:text="#string/slide_2_desc"
android:textAlignment="center"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_desc" />
</LinearLayout>
</RelativeLayout>
After this line in your adapter :
View v = inflater.inflate(layouts[position],container,false);
Add:
TextView tv =(TextView) v.findViewById(R.id.yourTextView);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do your stuff here whatever you want to do upon click
}});
public class IntroFragment_1 extends Fragment {
private String title;
private int page;
ImageView intro_images_1;
Animation xmlAnimationSample;
// newInstance constructor for creating fragment with arguments
public static IntroFragment_1 newInstance(int page, String title) {
IntroFragment_1 fragmentFirst = new IntroFragment_1();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.intro_view_1, container, false);
intro_images_1 = view.findViewById(R.id.intro_images_1);
xmlAnimationSample = AnimationUtils.loadAnimation(getContext(),R.anim.zoom_intro);
intro_images_1.startAnimation(xmlAnimationSample);
return view;
}
}
MyViewPagerAdapter
public static class MyViewPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 3;
public MyViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return IntroFragment_1.newInstance(0, "Page # 1");
case 1: // Fragment # 0 - This will show FirstFragment different title
return IntroFragment_1.newInstance(0, "Page # 1");
case 2: // Fragment # 1 - This will show SecondFragment
return IntroFragment_1.newInstance(0, "Page # 1");
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
layouts = new int[]{0, 1, 2,};

How to get proper item in listview?

I writing test application and I get a strange behavior of mainActivity.listItem, when I click on item yet another item can get visible,it can get dissapear by scrolling.I'm confused.Thanks!
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stethoInit();
mainActivity = DataBindingUtil.setContentView(this, R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
cursor = getContentResolver().query(MyProvider.CONTENT_URI, null, null, null, null, null);
}
String[] from = new String[]{MyProvider.ID, MyProvider.TEXT};
int[] to = new int[]{R.id.t_id, R.id.t_text};
scAdapter = new SimpleCursorAdapter(this, R.layout.item, cursor, from, to, 0);
mainActivity.listItem.setAdapter(scAdapter);
scAdapter.notifyDataSetChanged();
mainActivity.listItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FrameLayout v = (FrameLayout)view.findViewById(R.id.updateLayout);
Log.d("!!!",v.toString());
v.setVisibility(View.VISIBLE);
}
});
mainActivity.insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment insertFragment = new Insert();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, insertFragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
});
}
item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/updateLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone">
<!-- TODO: Update blank fragment layout -->
<EditText
android:id="#+id/updateTextField"
android:layout_width="match_parent"
android:layout_height="50dp"
android:ems="10"
android:hint="#string/insertTextFieldHint"
android:focusable="false"
android:inputType="textPersonName" />
<Button
android:id="#+id/uodateRecButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="125dp"
android:layout_marginTop="65dp"
android:focusable="false"
android:text="#string/updateRecButton" />
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"/>
<TextView
android:id="#+id/t_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:id="#+id/t_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
UPDATE
I solved this problem by extending SimpleCursorAdapter ,maybe someone share with another solution?
private class MyAdapter extends SimpleCursorAdapter{
private int layout;
public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
this.layout = layout;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
String id = cursor.getString(colId);
String title = cursor.getString(colText);
TextView idView = (TextView)view.findViewById(R.id.t_id);
idView.setText(id);
TextView textView = (TextView)view.findViewById(R.id.t_text);
textView.setText(title);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = getLayoutInflater().inflate(layout,parent,false);
return view;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return getCount();
}
}

design layout like this image what is use to design

[ http://i.stack.imgur.com/Re29U.png]
left right swipe center value automatically checked and related table show in layout.
try this
MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView[] dots;
private LinearLayout dotsLayout;
// Declare Variables
ViewPager viewPager;
String[] CustomerNameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomerNameList = new String[]{"xxxxx", "sssss", "aaaaaa", "ffffff", "gggggggg", "jjjjj"};
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
addBottomDots(0);
// Locate the ViewPager in viewpager_main.xml
viewPager = (ViewPager) findViewById(R.id.first_customer_popup_view_pager);
// Pass results to ViewPagerAdapter Class
CustomPagerAdapter adapter = new CustomPagerAdapter(this, CustomerNameList);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
private void addBottomDots(int currentPage) {
dots = new TextView[CustomerNameList.length];
int colorsActive = Color.rgb(102, 41, 125);
int colorsInactive = Color.rgb(217, 217, 217);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(100);
dots[i].setTextColor(colorsInactive);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive);
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
}
CustomPagerAdapter.java
public class CustomPagerAdapter extends PagerAdapter {
private Context context;
private String[] CustomerNameList;
LayoutInflater inflater;
public CustomPagerAdapter(Context context,String[] CustomerNameList) {
this.context = context;
this.CustomerNameList = CustomerNameList;
}
#Override
public int getCount() {
return CustomerNameList.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Declare Variables
TextView AO_investments_list_popup_name;
TextView AO_investments_list_popup_na;
ListView all_listView;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.adapter_single_page, container, false);
// Locate the TextViews in viewpager_item.xml
AO_investments_list_popup_name = (TextView) itemView.findViewById(R.id.display);
AO_investments_list_popup_name.setText(CustomerNameList[position]);
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.agthamays.sof_1.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/first_customer_popup_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true" />
<LinearLayout
android:id="#+id/layoutDots"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#color/colorAccent"
android:gravity="center|center_vertical"
android:orientation="horizontal">
</LinearLayout>
</RelativeLayout>
</LinearLayout>
adapter_single_page.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:background="#color/colorPrimaryDark"
android:orientation="horizontal"
android:layout_height="wrap_content">
<TextView
android:id="#+id/display"
android:layout_width="wrap_content"
android:text="xxxx"
android:textSize="24dp"
android:paddingLeft="100dp"
android:textStyle="bold"
android:textColor="#color/colorAccent"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</LinearLayout>

How to get items selected from checked listview on viewpager?

I am using a viewpager in my program and on that I am displaying custom listview. On every viewpager swipe I am displaying the same listview but with differnt list items. I want to get all the items checked from all those listviews, when I click on the submit button.
But this submit button is not on my viewpager. Its quite complicated for me. Here is my main class code(I am just showing part of my code there are no errors in the code right now):
public class HotelMenu extends FragmentActivity implements CompletionListener {
static final int ITEMS = 10;
MyAdapter mAdapter;
ViewPager mPager;
private NetworkTask networkTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_menu);
get_restaurant_menu();
mAdapter = new MyAdapter(getSupportFragmentManager(),HotelMenu.this);
mPager = (ViewPager) findViewById(R.id.pager);//adapter for viewpager
Button submit= (Button) findViewById(R.id.next);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//here I want all the items checked from the listview
}
});
}
Here is my layout for this class:
<?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:gravity="center_horizontal"
android:orientation="vertical"
android:padding="4dip"
android:background="#drawable/home_screen_background">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tvRestNameForMenu"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#ffffff"
android:layout_gravity="center_vertical"
android:background="#drawable/offers_text"
/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:alpha="0.7"
android:background="#android:color/white">
</android.support.v4.view.ViewPager>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center"
android:measureWithLargestChild="true"
android:orientation="horizontal" >
<Button
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:background="#drawable/button_shape"
android:textColor="#android:color/white">
</Button>
</LinearLayout>
</LinearLayout>
This is my adpater for viewpager:
public static class MyAdapter extends FragmentStatePagerAdapter {
Context context;
public MyAdapter(FragmentManager fragmentManager, Context context) {
super(fragmentManager);
this.context=context;
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show list of maincourse items
// return ArrayListFragment.newInstance(position, mainCourse);//pass viewpager page position and list to be displayed
case 1: // Fragment # 1 - This will show list of soups
return ArrayListFragment.newInstance(position,startersName,startersCost );
default:// Fragment # 2-9 - Will show list
return ArrayListFragment.newInstance(position, maincourseName,maincourseCost);
}
}
}
and finally this is my fragment for displaying listview on viewpager:
public class ArrayListFragment extends android.support.v4.app.Fragment{
int fragNum;
String[] arr;
ArrayList<String>item_name;
ArrayList<String>item_cost;
ListView lvsoups;
MyAdapter myAdapter;
Context context;
LayoutInflater inflater1;
View layoutView;
public static final ArrayListFragment newInstance(int val, ArrayList<String> itemName, ArrayList<String> itemCost){
ArrayListFragment list=new ArrayListFragment();
//Bundle is used to use values and array passed through hotel menu class
Bundle bundle = new Bundle(2);
bundle.putInt("val", val);
bundle.putStringArrayList("itemName",itemName);
bundle.putStringArrayList("itemCost",itemCost);
list.setArguments(bundle);
return list ;
}
/**
* Retrieving this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//init passed values
fragNum = getArguments() != null ? getArguments().getInt("val") : 1;
item_name=getArguments().getStringArrayList("itemName");
item_cost=getArguments().getStringArrayList("itemCost");
}
/**
* to set view to the fragment activity
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.fragment_pager_list,
container, false);
lvsoups = (ListView) layoutView.findViewById(R.id.listMenu);
myAdapter = new MyAdapter(getActivity(), item_name,item_cost);
lvsoups.setAdapter(myAdapter);//set adapter to the list view
return layoutView;
}
//adapter for the listview
public class MyAdapter extends BaseAdapter {
ArrayList<String> itemName;
ArrayList<String> itemCost;
Context context;
LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<String> item_name, ArrayList<String> item_cost) {
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(item_name!=null)
{
// arr = new String[objects.length];
this.itemName = item_name;
this.itemCost=item_cost;
}
}
#Override
public int getCount() {
return itemName.size();
}
#Override
public Object getItem(int position) {
return itemName.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int value;
View menuRow = inflater.inflate(R.layout.hotel_menu_list_item, null);
TextView tvSoups = (TextView) menuRow.findViewById(R.id.tvMenuItem); //To set name of menu item, for example Corn Soup
TextView tvPrice = (TextView) menuRow.findViewById(R.id.tvMenuPrice); //To set price of that item
CheckBox cbQty = (CheckBox) menuRow.findViewById(R.id.cbMenuItem);
Spinner spQty = (Spinner) menuRow.findViewById(R.id.spinnerQty);
String[] quantity = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
ArrayAdapter spinnerAdapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, quantity);
spQty.setAdapter(spinnerAdapter);
tvSoups.setText(itemName.get(position));
tvPrice.setText(itemCost.get(position));
Log.e("arr", itemName.get(position));
if (cbQty.isChecked()) {
value = 1;
} else {
value = 0;
}
menuRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent intent=new Intent(SearchResult.this,RestMainActivity.class);
// intent.putExtra("Hotel_Master_Id",hotelMasterIdList.get(position));
// startActivity(intent);
}
});
return menuRow;
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
This is my hotel_menu_list_item.xml :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:weightSum="5">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cbMenuItem" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:layout_weight="3"
android:id="#+id/tvMenuItem" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:layout_weight="1"
android:id="#+id/tvMenuPrice" />
<Spinner
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/spinnerQty"
android:layout_weight="1"
>
</Spinner>
</LinearLayout>

ActionBar 2 tabs, lists in each tab, row onClick not always firing

This might be a duplicate question, but I've looked through a lot of SO questions, but didn't find anything that helped.
I have an app that has 2 tabs using the ActionBar. Each is a ListFragment and I am unable to select any of the items on them. They will populate just fine, but the onListItemClick just won't fire. It also won't fire if I use setOnItemClickListener directly to my ListView. However, if I just extend Fragment and not ListFragment, if I attach an onClickListener to each row, that onClick will fire. But it will allow multiple rows to be clickable and this is not something I want to happen. Can anybody help me figure out what I'm doing wrong? Thanks in advance.
This is my MainActivity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the action bar
Drawable drawable = getResources().getDrawable(R.drawable.action_bar);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(drawable);
bar.addTab(bar.newTab().setText("Tab 1").setTabListener(new TabHandler()));
bar.addTab(bar.newTab().setText("Tab 2").setTabListener(new TabHandler()));
bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_USE_LOGO);
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowHomeEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
bar.setDisplayShowTitleEnabled(false);
}
}
This is my TabHandler:
public class TabHandler implements ActionBar.TabListener {
public Fragment mFragment;
public TabHandler() { }
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
switch (tab.getPosition()) {
case 0:
if(mFragment == null) {
mFragment = new ListFragmentA();
fragmentTransaction.add(android.R.id.content, mFragment, null);
}
else {
fragmentTransaction.show(mFragment); //Looking into detach and attach as well
}
break;
case 1:
if(mFragment == null) {
mFragment = new ListFragmentB();
fragmentTransaction.add(android.R.id.content, mFragment, null);
}
else {
fragmentTransaction.show(mFragment);
}
break;
default:
break;
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
if (mFragment != null) {
mFragment.getFragmentManager().popBackStackImmediate();
fragmentTransaction.hide(mFragment);
}
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mFragment.getFragmentManager().popBackStackImmediate();
}
}
This is an example of one of my fragments:
public class ListFragmentA extends ListFragment {
MyCustomAdapter myCustomAdapter;
ListView myListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_list_background,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(getActivity() != null) {
myListView = (ListView)getActivity().findViewById(android.R.id.list);
if(myListView != null) {
CrudService itemService = new CrudService<TestItem>(TestItem.class);
ArrayList<TestItem> myItems = (ArrayList<TestItem>) itemService.FindAll();
myCustomAdapter = new MyCustomAdapter(getActivity(), myItems);
myListView.setAdapter(myCustomAdapter);
myListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
myListView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.i("ListFragmentA", "MyListView onItemClick");
}
});
}
}
}
//This isn't getting fired
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("ListFragmentA", "onListItemClick at position " + position);
}
public class MyCustomAdapter extends ArrayAdapter<TestItem> {
Context mContext;
ArrayList<TestItem> mItems;
public MyCustomAdapter(Context context, ArrayList<TestItem> items) {
super(context, android.R.id.list, items);
mContext = context;
mItems = items;
}
public int getCount() {
return mItems.size();
}
public TestItem getItem(int position) {
return mItems.get(position);
}
public long getItemId(int position) {
return mItems.get(position).getId();
}
public View getView(final int position, View convertView, ViewGroup arg2) {
View rowView = convertView;
if(rowView == null) {
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.single_item, null);
TestItemViewHolder viewHolder = new TestItemViewHolder();
viewHolder.Name = (TextView)rowView.findViewById(R.id.txt_TestItem_Name);
//I have a few more things
rowView.setTag(viewHolder);
}
TestItemListViewHolder holder = (TestItemListViewHolder)rowView.getTag();
TestItem gottenItem = getItem(position);
holder.Name.setText(gottenItem.getName());
//I have a few more things
//However, this will fire if not a ListFragment
rowView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("ListFragmentA", "RowView onClick at position " + position);
}
});
return rowView;
}
}
}
Here is an example of my "my_list_background" xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Tab_Layout_A"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="5dp"
android:background="#color/white">
<!-- listview Title Layout -->
<LinearLayout
android:id="#+id/ll_Table_Title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_marginBottom="-15dp"
android:layout_marginTop="7dp"
android:layout_marginLeft="11dip"
android:layout_marginRight="11dip"
android:orientation="horizontal"
android:weightSum="100"
android:background="#color/black">
<TextView
android:id="#+id/txt_TestItem_Name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/Name"
android:textColor="#color/white"
android:textStyle="bold" />
<!--I have omitted the other columns-->
</LinearLayout>
<LinearLayout
android:id="#+id/message_List_Layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
</LinearLayout>
and an example of my "single_item" xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/single_row"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:weightSum="100">
<TextView
android:id="#+id/txt_TestItem_Name"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:padding="2dip"
android:layout_weight="25"
android:textColor="#color/black"/>
<ImageButton
android:id="#+id/btn_Next"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:padding="2dip"
android:layout_weight="2"
android:background="#drawable/disclosure_button"
android:contentDescription="#string/next_Button"/>
</LinearLayout>
Ok, so I found my problem. In my "single_item" xml file, I had a ImageButton that was stealing the focus. I swapped it to a ImageView and it works just fine.

Categories

Resources