I am using view pager in my activity.I created views for 7 pages. Now i want to access page view inside my activity. I am getting data as blank.
In Activity
public class ActivitySingleEntry extends Activity implements OnClickListener {
private ViewPager mPager;
private FixedTabsView mFixedTabs;
private ExamplePagerAdapter mPagerAdapter;
private TabsAdapter mFixedTabsAdapter;
private EditText edtFieldName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fixed_tabs);
initViewPager(7, 0xFFFFFFFF, 0xFF000000);
mFixedTabs = (FixedTabsView) findViewById(R.id.fixed_tabs);
mFixedTabsAdapter = new FixedTabsAdapter(this);
mFixedTabs.setAdapter(mFixedTabsAdapter);
mFixedTabs.setViewPager(mPager);
}
private void initViewPager(int pageCount, int backgroundColor, int textColor) {
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ExamplePagerAdapter(this, pageCount,
backgroundColor, textColor);
mPager.setAdapter(mPagerAdapter);
mPager.setCurrentItem(1);
mPager.setPageMargin(5);
}
#Override
public void onClick(View v) {
// LinearLayout lin=(LinearLayout) mPager.getChildAt(mPager.getCurrentItem());
// edtFieldName=(EditText) lin.findViewById(R.id.edtFieldName);
// Log.d("test", "From get child:"+edtFieldName.getText().toString()+":");
Log.d("test", "Current Page:"+mPager.getCurrentItem());
LinearLayout linearLayout=(LinearLayout) mPager.findViewWithTag("lin"+mPager.getCurrentItem());
edtFieldName=(EditText) linearLayout.findViewById(R.id.edtFieldName);
edtFieldName=(EditText) findViewById(R.id.edtFieldName);
if (edtFieldName==null) {
ShowToast.makeToast(getApplicationContext(), "Edt null");
}else
ShowToast.makeToast(getApplicationContext(),
"Data saved " + edtFieldName.getText().toString() + ":"
+ mPager.getCurrentItem());
}
}
My PageAdaper
public class ExamplePagerAdapter extends PagerAdapter {
protected transient Activity mContext;
private int mLength = 0;
private int mBackgroundColor = 0xFFFFFFFF;
private int mTextColor = 0xFF000000;
private String[] mData = { "Temperature", "Sugar", "BP", "Field 4",
"Field 5", "Field 6", "Field 7" };
public ExamplePagerAdapter(Activity context, int length,
int backgroundColor, int textColor) {
mContext = context;
mLength = length;
mBackgroundColor = backgroundColor;
mTextColor = textColor;
}
#Override
public int getCount() {
return mLength;
}
#Override
public Object instantiateItem(View container, int position) {
LinearLayout linearLayout = (LinearLayout) View.inflate(mContext,
R.layout.activity_single_entry, null);
TextView txtFieldName = (TextView) linearLayout
.findViewById(R.id.txtFieldName);
EditText edtFieldName = (EditText) linearLayout
.findViewById(R.id.edtFieldName);
String filedName = mData[position];
txtFieldName.setText(filedName);
edtFieldName.setHint("Please enter " + filedName);
edtFieldName.setInputType(InputType.TYPE_CLASS_TEXT);
if (filedName.equals("Temperature")) {
edtFieldName.setInputType(InputType.TYPE_CLASS_NUMBER);
} else if (filedName.equals("Sugar")) {
edtFieldName.setInputType(InputType.TYPE_CLASS_NUMBER);
} else if (filedName.equals("BP")) {
edtFieldName.setInputType(InputType.TYPE_CLASS_NUMBER);
}
edtFieldName.setTag("edt");
((ViewPager) container).addView(linearLayout, 0);
linearLayout.setTag("lin"+position);
Log.d("test", "Adapter creating item:"+position );
return linearLayout;
}
#Override
public void destroyItem(View container, int position, Object view) {
((ViewPager) container).removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((View) object);
}
#Override
public void finishUpdate(View container) {
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
In R.layout.activity_single_entry xml i have edittext and button with onclick.
MYXml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/txtFieldName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<EditText
android:id="#+id/edtFieldName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:hint="Please enter field value" />
</LinearLayout>
<Button
android:id="#+id/btnSave"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
android:layout_margin="20dp"
android:onClick="onClick"
/>
</LinearLayout>
If i used inside pageadapter
#Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
return POSITION_NONE;
}
OnClick of button i want to access data from edit text.
I able to get value for first page.Not for all.
firstm you setTag():
linearLayout.setTag("lin"+position);
where position is in <0..numPages-1>
but read it:
LinearLayout linearLayout=(LinearLayout) mPager.findViewWithTag("lin"+mPager.getCurrentItem());
is findViewWithTag returning null everywhere or only on the last page?
mPager.getCurrentItem() returns 0 if it is first page so there is no need to add +1 while reading
In page adapter i am using single view in each page so its refers to only first item.If i tried to get view for page its giving me only first object so i applied distinct id for edit text in each page.
In page adapter
#Override
public Object instantiateItem(View container, int position) {
LinearLayout linearLayout = (LinearLayout) View.inflate(mContext,
R.layout.activity_single_entry, null);
TextView txtFieldName = (TextView) linearLayout
.findViewById(R.id.txtFieldName);
EditText edtFieldName = (EditText) linearLayout
.findViewById(R.id.edtFieldName);
***edtFieldName.setId(position);***
String filedName = mData[position];
txtFieldName.setText(filedName);
edtFieldName.setHint("Please enter " + filedName);
edtFieldName.setInputType(InputType.TYPE_CLASS_TEXT);
if (filedName.equals("Temperature")) {
edtFieldName.setInputType(InputType.TYPE_CLASS_NUMBER);
} else if (filedName.equals("Sugar")) {
edtFieldName.setInputType(InputType.TYPE_CLASS_NUMBER);
} else if (filedName.equals("BP")) {
edtFieldName.setInputType(InputType.TYPE_CLASS_NUMBER);
}
edtFieldName.setTag("edt"+position);
((ViewPager) container).addView(linearLayout, 0);
mItems.add(linearLayout);
linearLayout.setTag("lin"+position);
Log.d("test", "Adapter creating item:"+position );
return linearLayout;
}
Its working now
A quick solution would be to keep a List in your ExamplePagerAdapter and add to it after your addView() call. Then you could implement a public function such as getItemAtPosition(int position) that returns the LinearLayout at that page of the ViewPager. Then you can run findViewById(R.id.edtFieldName) on that linear layout in your Activity. In code:
In your ExamplePagerAdapter, add a private object:
List<LinearLayout> mItems;
add in your constructor:
mItems = new Vector<LinearLayout>();
add in instantiateItem():
((ViewPager) container).addView(linearLayout, 0);
mItems.add(linearLayout);
then add a method:
public LinearLayout getItemAtPosition(int position) {
return mItems.get(position);
}
Then use that method in your Activity. Hope it's what you were looking for.
Related
I have a basket icon with count notification on it in actionbar for showing number of goods in shopping basket. also I have a custom view containing a button for add goods to shopping basket. I want that when I click on button (in custom view) notification count on basket icon increases. I use this function in main activity to update notification count but notification does not update.
public static void updateCountBasket(final int number , int id , View view ,Context context) {
if (view.findViewById(id) == null)
return;
TextView t = (TextView)view.findViewById(id);
String dd = t.getText().toString();
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
if (number == 0)
t.setVisibility(View.INVISIBLE);
else {
t.setVisibility(View.VISIBLE);
t.setText(Integer.toString(number));
}
}
});
}
but when I use non static of that function in main activity with simple button on click, it works fine. but I can't call non static function in base adapter too :( . I checked line by line of the function in static mode all ids are right and it set text too but nothing change or get error!!. please help me to change textview as notification of basket in menubar from base adapter when button in custom view clicks. thanks
I have this base adapter for my custom view list:
public class Goods_ImageAdapter extends BaseAdapter {
private Context context;
private final JSONArray Goods;
private Bagde bagde;
public Goods_ImageAdapter(Context context , JSONArray Goods) {
this.context = context;
this.Goods = Goods;
bagde = Bagde.getInstance();
}
#Override
public int getCount() {
return Goods.length();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
public static String doubleToStringNoDecimal(double d) {
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);;
formatter .applyPattern("#,###");
return formatter.format(d);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
final View bagde_c;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.goodsitem, null);
bagde_c = inflater.inflate(R.layout.badge_counter, null);
try {
TextView goods_textview_Name = (TextView) gridView.findViewById(R.id.goods_textview_Name);
goods_textview_Name.setText(Goods.getJSONObject(position).getString("Name"));
TextView goods_textview_Price = (TextView) gridView.findViewById(R.id.goods_textview_Price);
goods_textview_Price.setText(Goods.getJSONObject(position).getString("Price"));
} catch (JSONException e) {
e.printStackTrace();
}
try {
ImageView goods_imageview = (ImageView) gridView.findViewById(R.id.goods_imageview);
new ImageDownloader(goods_imageview).execute("http://IP/" + Goods.getJSONObject(position).getString("ImageFileName"));
} catch (JSONException e) {
e.printStackTrace();
}
final TextView goods_textview_bagdecounter = (TextView) gridView.findViewById(R.id.goods_textview_bagdecounter);
ImageView goods_buy_plus = (ImageView) gridView.findViewById(R.id.goods_buy_button_plus);
try {
goods_buy_plus.setTag(Goods.getJSONObject(position));
} catch (JSONException e) {
e.printStackTrace();
}
goods_buy_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
String bagde_counter_text = goods_textview_bagdecounter.getText().toString();
goods_textview_bagdecounter.setText(String.valueOf(Integer.parseInt(bagde_counter_text) + 1));
}
});
com.???.????.Goods_Activity.updateCountBasket(a number for example,R.id.notif,inflater2.inflate(R.layout.badge_counter, null),context);
}
});
ImageView goods_buy_minus = (ImageView) gridView.findViewById(R.id.goods_buy_button_minus);
try {
goods_buy_minus.setTag(Goods.getJSONObject(position));
} catch (JSONException e) {
e.printStackTrace();
}
goods_buy_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
String bagde_counter_text = goods_textview_bagdecounter.getText().toString();
if(Integer.parseInt(bagde_counter_text)> 0)
goods_textview_bagdecounter.setText(String.valueOf(Integer.parseInt(bagde_counter_text) - 1));
}
});
}
});
} else {
gridView = (View) convertView;
}
return gridView;
}
}
this is (basket with notification on action bar) badge_counter.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="#android:style/Widget.ActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="true"
android:gravity="center"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/badge_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/relative_layout_item_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/button"
android:layout_width="40dip"
android:layout_height="40dip"
android:background="#drawable/download" />
<TextView
android:id="#+id/notif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#android:drawable/ic_notification_overlay"
android:text="33"
android:textColor="#FFA"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
You can achieve this by using interface.
Add an interface in Adapter class
public interface AdapterCallBack
{
public void onChangeBadgeCount();
}
And in constructor, pass a reference to this interface.
public Goods_ImageAdapter(Context context , JSONArray Goods, AdapterCallBack adapterCallback)
{
this.context = context;
this.Goods = Goods;
this.adapterCallback = adapterCallback;
bagde = Bagde.getInstance();
}
And whenever you want to set badge count in ActionBar, just call adapterCallback.onChangeBadgeCount().
And implement this interface in MainActivity.
public class MainActivity implements Goods_ImageAdapter.AdapterCallBack
{
... some code
When your are initializing adapter, just pass this as a last parameter.
Example:
adapter = new Goods_ImageAdapter(this, Goods /* Json data */, this);
...
#override
public void onChangeBadgeCount()
{
// Change your badge count here
}
}
I am printing my array length size in ActionBar from Recycler adapter
((Show_request) mContext).getSupportActionBar().setTitle("Total Stone:- " + array.length());
Using this you can get ActionBar in RecyclerView adapter
((your activity name) context object).getSupportActionBar().setTitle("message"/or pass variable);
For my Android project, I have a listview which has a checkbox for every item. The data is loaded from an SQLite database by using a CursorAdapter class. However, whenever I scroll, the checkbox positions will get moved and get carried down to the next part of the listview. How can I fix this problem?
GIF of my CheckBox Problem
Here's my Cursor Adapter Class:
public class VocabCursorAdapter extends CursorAdapter {
private static final int DIFFICULT = 0;
private static final int FAMILIAR = 1;
private static final int EASY = 2;
private static final int PERFECT = 3;
public VocabCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_vocab, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvVocabName = (TextView) view.findViewById(R.id.vocabName);
TextView tvVocabDefinition = (TextView) view.findViewById(R.id.vocabDefinition);
ImageView tvVocabLevel = (ImageView) view.findViewById(R.id.vocabLevel);
// Extract properties from cursor
String vocab = cursor.getString(cursor.getColumnIndexOrThrow(VocabDbContract.COLUMN_NAME_VOCAB));
String definition = cursor.getString(cursor.getColumnIndexOrThrow(VocabDbContract.COLUMN_NAME_DEFINITION));
int level = cursor.getInt(cursor.getColumnIndexOrThrow(VocabDbContract.COLUMN_NAME_LEVEL));
// Populate fields with extracted properties
tvVocabName.setText(vocab);
tvVocabDefinition.setText(definition);
if (level == DIFFICULT) {
tvVocabLevel.setImageResource(R.drawable.level_bars_difficult);
tvVocabLevel.setTag(DIFFICULT);
}
else if (level == FAMILIAR) {
tvVocabLevel.setImageResource(R.drawable.level_bars_familiar);
tvVocabLevel.setTag(FAMILIAR);
}
else if (level == EASY) {
tvVocabLevel.setImageResource(R.drawable.level_bars_easy);
tvVocabLevel.setTag(EASY);
}
else if (level == PERFECT) {
tvVocabLevel.setImageResource(R.drawable.level_bars_perfect);
tvVocabLevel.setTag(PERFECT);
}
}
And here's my list item xml, item_vocab.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:longClickable="true">
<ImageView
android:layout_width="36sp"
android:layout_height="36sp"
android:id="#+id/vocabLevel"
android:layout_gravity="right"
android:src="#drawable/level_bars"
android:scaleType="fitXY"
android:contentDescription="#string/vocab_level"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/editCheckbox"
android:layout_toStartOf="#+id/editCheckbox"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/vocabName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/vocabLevel"
android:layout_toStartOf="#+id/vocabLevel"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/vocabDefinition"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/vocabLevel"
android:layout_toStartOf="#+id/vocabLevel"
android:layout_below="#id/vocabName"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editCheckbox"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
And here's my xml which contains a listview
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".controller.MyVocab"
android:paddingLeft="5dp">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/mVocabList"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/empty_text_view"
android:id="#android:id/empty"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
I have looked at a lot of different solutions on StackOverflow, but I wasn't able to successfully do it in my own app. For an example, this post has a similar problem, but its solution used getView and I had trouble understanding how to implement it with newView and bindView instead.
And some other solutions might be examples where a cursoradapter is not involved. Any help is much appreciated, thanks a lot!
Edit #1: After incorporating Phan's changes, the checkbox states get resets to false rather than keeping its states when I scroll the listview (See ).
Reason : ListView re-uses the views.
Solution :
class VocabCursorAdapter extends CursorAdapter {
List<Integer> selectedItemsPositions;//to store all selected items position
public VocabCursorAdapter(Context context, Cursor c,int flags) {
super(context, c,0);
selectedItemsPositions = new ArrayList<>();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
View view = LayoutInflater.from(context).inflate(R.layout.item_vocab, viewGroup, false);
CheckBox box = (CheckBox) view.findViewById(R.id.editCheckbox);
box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
int position = (int) compoundButton.getTag();
if (b) {
//check whether its already selected or not
if (!selectedItemsPositions.contains(position))
selectedItemsPositions.add(position);
} else {
//remove position if unchecked checked item
selectedItemsPositions.remove((Object) position);
}
}
});
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
//your other stuff
CheckBox box = (CheckBox) view.findViewById(R.id.editCheckbox);
box.setTag(cursor.getPosition());
if (selectedItemsPositions.contains(cursor.getPosition()))
box.setChecked(true);
else
box.setChecked(false);
}
}
Try this
public class VocabCursorAdapter extends CursorAdapter {
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>(); // array list for store state of each checkbox
public VocabCursorAdapter(Context context, Cursor c, int flags) {
for (int i = 0; i < c.getCount(); i++) { // c.getCount() return total number of your Cursor
itemChecked.add(i, false); // initializes all items value with false
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
...
final int position = cursor.getPosition(); // get position by cursor
CheckBox checkBox = (CheckBox) view.findViewById(R.id.editCheckbox);
checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (itemChecked.get(position) == true) { // if current checkbox is checked, when you click -> change it to false
itemChecked.set(position, false);
} else {
itemChecked.set(position, true);
}
}
});
checkBox.setChecked(itemChecked.get(position)); // set the checkbox state base on arraylist object state
Log.i("In VocabCursorAdapter","position: "+position+" - checkbox state: "+itemChecked.get(position));
}
}
public class ObservationselectattributeFragment extends Fragment {
DatabaseHandler mDBHandler;
ListView mListView;
SimpleCursorAdapter mSCA;
Cursor mCsr;
ArrayList<String> attributeItems = new ArrayList<>();
public ObservationselectattributeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the layout for this fragment
View view1=inflater.inflate(R.layout.fragment_observationselectattribute, container, false);
//Bundle bundle2 = getArguments();
Bundle bundle1 = getArguments();
final int firsttext= bundle1.getInt("TotalCount");
final String selectedtreatment= bundle1.getString("SelectedTreatment");
Toast.makeText(getActivity(),"value \n"+firsttext+"\n"+"treatment \n"+selectedtreatment, Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(),"SelectedTreatment \n"+selectedtreatment, Toast.LENGTH_SHORT).show();
mListView = (ListView)view1.findViewById(R.id.lv001);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button addattribute = (Button)view1.findViewById(R.id.addattribute);
addattribute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String items1="";
Integer tcount1=0;
for(String item1:attributeItems){
items1+="-"+item1+"\n";
tcount1++;
}
Toast.makeText(getActivity(),"you have selected \n"+items1,Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(),"you have selected \n"+tcount1,Toast.LENGTH_LONG).show();
/*FragmentTransaction fr= getFragmentManager().beginTransaction();
fr.replace(R.id.main_container, new ShowObservationDataRecordingFragment()).addToBackStack("ObservationselectattributeFragment");
fr.commit();*/
Bundle bundle = new Bundle();
bundle.putInt("TotalCount2",firsttext);
bundle.putInt("TotalCount1", tcount1);
bundle.putString("SelectedTreatment", selectedtreatment);
Fragment showobservationdatarecordingfragment = new ShowObservationDataRecordingFragment();
showobservationdatarecordingfragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_container, showobservationdatarecordingfragment).addToBackStack("ObservationselectattributeFragment").commit();
}
});
mDBHandler = new DatabaseHandler(this.getActivity());
mCsr = mDBHandler.getAllRecords();
// Prepare a list of the columns to get the data from, for the ListViewt
String[] columns_to_get_data_from = new String[]{
DatabaseHandler.KEY_IDS,
DatabaseHandler.KEY_NAMES,
DatabaseHandler.KEY_FNAME,
DatabaseHandler.KEY_MONAME,
DatabaseHandler.KEY_SNAME
};
// Prepare a list of the Views into which to place the data
int[] itemviews_to_place_data_in = new int[]{
R.id.euserid,
R.id.eusername,
R.id.efname,
R.id.emoname,
R.id.esname
};
// get and instance of SimpleCursorAdapter
mSCA = new SimpleCursorAdapter(getActivity(),
R.layout.listviewitem_record,
mCsr,
columns_to_get_data_from,
itemviews_to_place_data_in,
0);
// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = mListView.onSaveInstanceState();
// get and instance of SimpleCursorAdapter the listviewitem_record layout
mListView.setAdapter(mSCA);
// Restore previous state (including selected item index and scroll position)
mListView.onRestoreInstanceState(state);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String attributeItem1 = ((TextView)view.findViewById(R.id.euserid)).getText().toString();
String attributeItem2 = ((TextView)view.findViewById(R.id.eusername)).getText().toString();
String attributeItem3 = ((TextView)view.findViewById(R.id.efname)).getText().toString();
String attributeItem4 = ((TextView)view.findViewById(R.id.emoname)).getText().toString();
String attributeItem5 = ((TextView)view.findViewById(R.id.esname)).getText().toString();
String attributeItem = attributeItem1 + attributeItem2 + attributeItem3 + attributeItem4 + attributeItem5;
// CheckedTextView box = (CheckedTextView) view.findViewById(R.id.record_checkbox);
// box.setChecked(true);
CheckedTextView checkedTextView = (CheckedTextView) view.findViewById(R.id.record_checkbox);
if(checkedTextView.isChecked()) {
checkedTextView.setChecked(false);
} else {
checkedTextView.setChecked(true);
}
if(attributeItems.contains(attributeItem)){
attributeItems.remove(attributeItem);//uncheck item
}
else
{
attributeItems.add(attributeItem);
}
Toast.makeText(getActivity(), "Item1 = " + attributeItem1 +"\n"+ "Item2 ="+attributeItem2 +"\n"+"Item3 ="+attributeItem3+"\n"+"Item4 ="+attributeItem4+"\n"+"Item5 ="+attributeItem5, Toast.LENGTH_SHORT).show();
}
});
((HomeActivity) getActivity())
.setActionBarTitle("Select Attribute");
return view1;
}
}
I'm fairly new to Android programming, and I'm trying to design an app where when I swipe through several images on a ViewPager that takes up some of the screen, other elements of that same activity/screen will change with it without necessarily 'scrolling' horizontally like the ViewPager does. My problem is that I can't find a way to identify which image in the ViewPager is the 'current' one outside of the ViewPager.
I tried to create a getter for grabbing the position from instantiateItem method, but no luck - because I assume it simply creates everything once, not updating it again, so when I swipe nothing will happen. Also, I realize that my dieValue variable doesn't do anything - but it's meant to serve as an example of what I want to accomplish. The dieValue variable would change based on which image was the current one.
CustomSwipeAdapter.java
public class CustomSwipeAdapter extends PagerAdapter {
private Context ctx;
public int[] image_resources = {R.drawable.d20, R.drawable.d8, R.drawable.d6};
public CustomSwipeAdapter(Context ctx) {
this.ctx = ctx;
}
#Override
public int getCount() {
return image_resources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.swipe_layout, container, false);
ImageView imageView = (ImageView) item_view.findViewById(R.id.dieImageView);
imageView.setImageResource(image_resources[position]);
TextView textView = (TextView) item_view.findViewById(R.id.dieValueTop);
if (position == 0) { textView.setText(R.string.d20Label); }
if (position == 1) { textView.setText(R.string.d8Label); }
if (position == 2) { textView.setText(R.string.d6Label); }
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
DiceRollerActivity.java
public class DiceRollerActivity extends Activity implements View.OnClickListener {
ViewPager viewPager;
CustomSwipeAdapter adapter;
private int dieValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dice_roller);
viewPager = (ViewPager) findViewById(R.id.dieViewPager);
adapter = new CustomSwipeAdapter(this);
viewPager.setAdapter(adapter);
Button RollDieButton = (Button) findViewById(R.id.rollDieButton);
RollDieButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.rollDieButton:
Random rand = new Random();
int random = rand.nextInt(dieValue) + 1;
setDieResults(random);
}
}
// Prints the results of the die roll to the results log
private void setDieResults(int random) {
TextView dieResults = (TextView) findViewById(R.id.dieResultsLabel);
if (random == dieValue) {
dieResults.setText(getString(R.string.YouRolledLabel) + random + getString(R.string.criticalHit));
} else if (random == dieValue) {
dieResults.setText(getString(R.string.YouRolledLabel) + random + getString(R.string.criticalMiss));
}else{
dieResults.setText(getString(R.string.YouRolledLabel) + random);
}
}
}
Create a method inside your CustomSwipeAdapter
public int getCurrentImageResource(int currentPosition){
return image_resources[currentPosition];
}
To access to the current image call this method passing current position with viewPager.getCurrentItem() like this
adapter.getCurrentImageResource(viewPager.getCurrentItem());
Hope this helps!
You could use
viewPager.getCurrentItem();
on your DiceRollerActivity.class to get the current position.
Then, to get the image a better approach would be to have the image array on your DiceRollerActivity.class and pass it onto the CustomSwipeAdapter constructor.
I'm trying to change the FragmentList item background color after click on this item an confirm an AlertDialog that is shown, it works but it's changing others items beside the clicled item....
This is all my code below...
public class RefrigeranteFragment extends ListFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public View SelectedView;
String[] refrigerantes = new String[] {
"Coca Cola",
"Coca Cola Zero",
"Fanta Uva",
"Guaraná Antartica",
"Guaraná Antartica Zero",
"Sukita",
"Sukita Laranja",
"Sprite",
"Guaraná Antartica",
"Sukita Uva"
};
// Array of strings to store currencies
String[] precos = new String[]{
"02,50",
"03,00",
"02,00",
"04,50",
"02,50",
"03,45",
"01,50",
"03,90",
"07,00",
"04,50"
};
int[] icones = new int[]{
R.drawable.ic_coca_lata,
R.drawable.ic_coca_zero_lata,
R.drawable.ic_fanta_uva_lata,
R.drawable.ic_guarana_antartica_lata,
R.drawable.ic_guarana_antartica_zero_lata,
R.drawable.ic_sukita_uva_lata,
R.drawable.ic_sukita_laranja_lata,
R.drawable.ic_sprite_lata,
R.drawable.ic_guarana_antartica_pet,
R.drawable.ic_sukita_uva_pet
};
private OnFragmentInteractionListener mListener;
public RefrigeranteFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static RefrigeranteFragment newInstance(String param1, String param2) {
RefrigeranteFragment fragment = new RefrigeranteFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 10; i++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("txtNome", refrigerantes[i]);
hm.put("txtPreco", precos[i]);
hm.put("img_refrigerante", Integer.toString(icones[i]));
aList.add(hm);
}
String[] from = {"img_refrigerante", "txtNome", "txtPreco"};
int[] to = {R.id.img_refrigerante, R.id.txtNome, R.id.txtPreco};
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.listview_refrigerante_layout, from, to);
setListAdapter(adapter);
// Inflate the layout for this fragment
return super.onCreateView(inflater, container, savedInstanceState);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onListItemClick(ListView listView, View view, int position, long id){
super.onListItemClick(listView, view, position, id);
final View v = view;
final TextView txt = (TextView)view.findViewById(R.id.txtNome);
final ImageView imageView = (ImageView)view.findViewById(R.id.img_refrigerante);
final TextView tvQuantity = (TextView)view.findViewById(R.id.txtQtde);
final TextView lblQuantity = (TextView)view.findViewById(R.id.lblQtde);
final NumberPicker txtQtde = new NumberPicker(getContext());
txtQtde.setMinValue(1);
txtQtde.setMaxValue(10);
if(tvQuantity.getText() != "")
txtQtde.setValue(Integer.parseInt(tvQuantity.getText().toString()));
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(txt.getText());
builder.setMessage("Informe a quantidade");
builder.setIcon(imageView.getDrawable());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
txtQtde.setLayoutParams(lp);
builder.setView(txtQtde);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
tvQuantity.setText(String.valueOf(txtQtde.getValue()));
tvQuantity.setVisibility(View.VISIBLE);
lblQuantity.setVisibility(View.VISIBLE);
v.setBackgroundColor(Color.parseColor("#FF9933"));
((TextView)v.findViewById(R.id.lblNome)).setTextColor(Color.WHITE);
((TextView)v.findViewById(R.id.txtNome)).setTextColor(Color.WHITE);
((TextView)v.findViewById(R.id.lblPreco)).setTextColor(Color.WHITE);
((TextView)v.findViewById(R.id.txtPreco)).setTextColor(Color.WHITE);
((TextView)v.findViewById(R.id.lblQtde)).setTextColor(Color.WHITE);
((TextView)v.findViewById(R.id.txtQtde)).setTextColor(Color.WHITE);
}
});
builder.setNegativeButton("Cancelar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}
);
builder.show();
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ImageView
android:id="#+id/img_refrigerante"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/pizza_fragment"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:src="#drawable/ic_menu_pizza2" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/img_refrigerante" >
<TextView
android:id="#+id/lblNome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Refrigerante: "
android:textStyle="bold"
android:textSize="15dp"
android:layout_below="#id/img_pizza" />
<TextView
android:id="#+id/txtNome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:layout_toRightOf="#+id/lblNome" />
<TextView
android:id="#+id/lblPreco"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Preço: "
android:textStyle="bold"
android:textSize="15dp"
android:layout_below="#+id/txtNome" />
<TextView
android:id="#+id/txtPreco"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:layout_toRightOf="#+id/lblPreco"
android:layout_below="#+id/txtNome" />
<TextView
android:id="#+id/lblQtde"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Qtde.: "
android:textStyle="bold"
android:textSize="15dp"
android:visibility="invisible"
android:layout_below="#+id/txtPreco" />
<TextView
android:id="#+id/txtQtde"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:visibility="invisible"
android:layout_toRightOf="#+id/lblQtde"
android:layout_below="#+id/txtPreco" />
</RelativeLayout>
</RelativeLayout>
That is happening because of view recycling within ListView.
In order for this to work, you need three things:
You need variables in your adapter that stores the "clicked" state of the items; for example, a list of booleans.
In your onListItemClick(), you need to call a method on the adapter to change the state of the current item and call notifyDataSetChanged().
In your getView() override, you need to check this state and set the background of the view you are creating accordingly.
Here's code for an adapter (inner class for your activity) that remembers if an item has been clicked (and also the quantity):
public static class MyListAdapter extends BaseAdapter {
private String[] mNames;
private String[] mPrices;
private int[] mIcons;
private int[] mQtys;
private boolean[] mClicked;
public MyListAdapter(String[] names, String[] prices, int[] icons) {
mNames = names;
mPrices = prices;
mIcons = icons;
mQtys = new int[names.length];
mClicked = new boolean[names.length];
}
#Override
public int getCount() {
return mNames.length;
}
#Override
public Object getItem(int position) {
return mNames[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_refrigerante_layout, parent, false);
}
ImageView icon = (ImageView) convertView.findViewById(R.id.img_refrigerante);
icon.setImageResource(mIcons[position]);
TextView name = (TextView) convertView.findViewById(R.id.txtNome);
name.setText(mNames[position]);
TextView price = (TextView) convertView.findViewById(R.id.txtPreco);
price.setText(mPrices[position]);
// hide these if qty == 0
TextView qty = (TextView) convertView.findViewById(R.id.txtQtde);
qty.setText(mQtys[position]);
qty.setVisibility(mQtys[position] == 0 ? View.INVISIBLE : View.VISIBLE);
TextView qtyLbl = (TextView) convertView.findViewById(R.id.lblQtde);
qtyLbl.setVisibility(mQtys[position] == 0 ? View.INVISIBLE : View.VISIBLE);
// here is where we use the clicked flag to determine which colors to set
// TODO put a real color for backgroundColorNormal because I don't know what your normal background color is
int backgroundColor = mClicked[position] ? Color.parseColor("#FF9933") : backgroundColorNormal;
convertView.setBackgroundColor(backgroundColor);
// TODO put a real color for colorNormal because I don't know what your normal text color is
int textColor = mClicked[position] ? Color.WHITE : colorNormal;
((TextView) convertView.findViewById(R.id.lblNome)).setTextColor(textColor);
((TextView) convertView.findViewById(R.id.txtNome)).setTextColor(textColor);
((TextView) convertView.findViewById(R.id.lblPreco)).setTextColor(textColor);
((TextView) convertView.findViewById(R.id.txtPreco)).setTextColor(textColor);
((TextView) convertView.findViewById(R.id.lblQtde)).setTextColor(textColor);
((TextView) convertView.findViewById(R.id.txtQtde)).setTextColor(textColor);
return convertView;
}
public int getQty(int position) {
return mQtys[position];
}
public void setQty(int position, int qty) {
mQtys[position] = qty;
notifyDataSetChanged();
}
public void setClicked(int position, boolean clicked) {
mClicked[position] = clicked;
notifyDataSetChanged();
}
}
When you change a click flag or quantity, notifyDataSetChanged() is called. This is what tells the ListView to ask the adapter again for item views through getView(), and the item views are updated using the new values.
You need to keep a reference to this adapter in your activity:
private MyListAdapter mAdapter;
and set it up:
mAdapter = new MyListAdapter(refrigerantes, precos, icones);
setListAdapter(mAdapter);
then your item click handler would look like this (I simplified it a bit)
#Override
public void onListItemClick(ListView listView, View view, final int position, long id){
super.onListItemClick(listView, view, position, id);
final NumberPicker txtQtde = new NumberPicker(getContext());
txtQtde.setMinValue(1);
txtQtde.setMaxValue(10);
txtQtde.setValue(Integer.parseInt(mAdapter.getQty(position)));
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(refrigerantes[position]);
builder.setMessage("Informe a quantidade");
builder.setIcon(icones[position]);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
txtQtde.setLayoutParams(lp);
builder.setView(txtQtde);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mAdapter.setQty(position, txtQtde.getValue());
mAdapter.setClicked(position);
}
});
builder.setNegativeButton("Cancelar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}
);
builder.show();
}
Please -- do more than just copy/paste this and take the time to go through the code line by line to understand how it works. Looking at sample code is a good way to learn about Android, but you won't learn anything if you copy/paste without understanding.
In this link I showed how to change item background color in AlertDialog. It also shows how to customize the AletDialog. For example, how to change divider colro and etc. Please visit this link:
https://stackoverflow.com/a/33439849/5475941.
I hope it helps.
I am implementing android GridviewPager android wear application. with the help of this code sample.
I want to display 2 action buttons, its onClick events, its text, background image. current code is looks like , in round wear emulator
and square emulator
my questions are.
1) How to remove top most black part in round emulator
2) Center image and text in square emulator
3) Perform onClick events on action buttons click
GridPagerAdapter
public class GridPagerAdapter extends FragmentGridPagerAdapter{
private Context mContext;
private ArrayList<GridRow> mRows;
public GridPagerAdapter(Context mContext, FragmentManager fm) {
super(fm);
this.mContext = mContext;
initAdapter();
}
private void initAdapter() {
mRows = new ArrayList<GridRow>();
GridRow row1 = new GridRow();
row1.addPage(new GridPage("", " Add Call", R.drawable.addcall, R.mipmap.ic_launcher));
row1.addPage(new GridPage("", " View Map", R.drawable.view_map, R.mipmap.ic_launcher));
mRows.add(row1);
}
#Override
public Fragment instantiateItem(ViewGroup container, int row, int column) {
Log.d("GridPagerAdapter","in instantiateItem row = "+row+"column = "+column);
return super.instantiateItem(container, row, column);
}
#Override
public Fragment getFragment(int row, int col) {
GridPage page = mRows.get(row).getPage(col);
Log.d("GridPagerAdapter","in getFragment row = "+row+"column = "+col);
CardFragment cardFragment = CardFragment.create(page.getTitle(), page.getText(), page.getIcon());
return cardFragment;
}
#Override
public Drawable getBackgroundForPage(int row, int column) {
GridPage page = mRows.get(row).getPage(column);
return getBackgroundForRow(page.getBackground());
}
#Override
public int getRowCount() {
return mRows.size();
}
#Override
public int getColumnCount(int row) {
return mRows.get(row).getSize();
}
}
Wear Activity
public class WearActivity extends Activity {
private GridViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wear);
mPager = (GridViewPager) findViewById(R.id.gridPager);
mPager.setAdapter(new GridPagerAdapter(this, getFragmentManager()));
}
}
Thanks for help in advance
Finally get the answer
1) Add following code in one of xml (rect,round)
<ImageView
android:id="#+id/imgview"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="35dp"
android:layout_gravity="center_horizontal"
android:src="#drawable/card1"/>
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
android:text="#string/hello_square" />
2) Edit instantiateItem method
#Override
public Object instantiateItem(ViewGroup viewGroup, final int row, final int col) {
final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.rect_activity_wear, viewGroup, false);
final TextView textView = (TextView) view.findViewById(R.id.text);
final ImageView imageView = (ImageView) view.findViewById(R.id.imgview);
imageView.setImageResource(carImageIDs[row][col]);
textView.setText(ImageTexts[row][col]);
viewGroup.addView(view);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Wear","Image Click row = "+row+"col = "+col);
}
});
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Wear","text Click row = "+row+"col = "+col);
}
});
return view;
}
Hope it helps someone , happy coding