I have one quote application which has a "Load more" button visible only if the quote list size is 15. Now I want change the condition so that it must show the button only if the quote list size is more than 15. My current code is like below and I have tried to change it to:
if(c.getCount()<=15){
// Not Showing Load More Button
}
but it's not showing my button.
My code for that button is below:
final Button btnLoadMore=new Button(this);
btnLoadMore.setBackgroundColor(Color.parseColor("#351802"));
btnLoadMore.setTextColor(Color.parseColor("#e8d8a7"));
btnLoadMore.setTypeface(btnLoadMore.getTypeface(), Typeface.BOLD);
btnLoadMore.setText("Load More Quotes");
if(c.getCount()<15){
// Not Showing Load More Button
}
else {
list.addFooterView(btnLoadMore);}
list.setAdapter(adapter);
anifadein=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slidedown);
list.startAnimation(anifadein);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
map = quotesList.get(position);
Intent intent = new Intent(QuotesActivity.this,
QuoteDialogActivity.class);
int itemPosition = position;
if(startingPoint>=30){
intent.putExtra("Pos", itemPosition+1);
intent.putExtra("LstCount", list.getCount()-1);
}else{
intent.putExtra("Pos", itemPosition+1);
intent.putExtra("LstCount", list.getCount());}
intent.putExtra("QuoteId", map.get(KEY_ID));
intent.putExtra("quotesType", quType);
intent.putExtra("startFrom", getIntent().getStringExtra("startFrom"));
intent.putExtra("Quotes", quotesList);
// Log.i("COUNT",""+(itemPosition+1)+"-"+list.getCount());
intent.putExtra("Fav", map.get(KEY_FAVORITE));
startActivity(intent);
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
}
});
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(btnLoadMore.getVisibility()==View.VISIBLE){
Cursor newC = null;
if (quType != 0) {
switch (quType) {
case 1:
newC = db.getQuotes(""+startingPoint);
break;
case 2:
newC = db.getFavoriteQuotes(""+startingPoint);
//page.setVisibility(View.GONE);
break;
case 3:
newC = db.getAuthorQuotes(getIntent().getStringExtra("AuthorId"),""+startingPoint);
// page.setVisibility(View.GONE);
break;
}
}
// Starting a new async task
if(newC.getCount()<15){
btnLoadMore.setVisibility(View.INVISIBLE);
}
startingPoint+=15;
do{
map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, newC.getString(newC.getColumnIndex(KEY_ID)));
map.put(KEY_TEXT, newC.getString(newC.getColumnIndex(KEY_TEXT)));
map.put(KEY_AUTHOR, newC.getString(newC.getColumnIndex(KEY_AUTHOR)));
map.put(KEY_PICTURE, newC.getString(newC.getColumnIndex(KEY_PICTURE)));
map.put(KEY_PICTURE_SDCARD, String.valueOf(newC.getInt(newC
.getColumnIndex(KEY_PICTURE_SDCARD))));
map.put(KEY_WEB_ID,
String.valueOf(newC.getInt(newC.getColumnIndex(KEY_WEB_ID))));
//Log.i("web_id",String.valueOf(newC.getInt(newC.getColumnIndex(KEY_ID))));
map.put(KEY_FAVORITE, newC.getString(newC.getColumnIndex(KEY_FAVORITE)));
// adding HashList to ArrayList
quotesList.add(map);
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
} while (newC.moveToNext());
adapter.notifyDataSetChanged(); }}
});
}
}
I not sure from where Object "c" is coming but i m assuming it list object and getCount is return the current count of list. So, If you want to show "Show more" button when the size of list is greater than or equals to 15 then use this condition.
if(c.getCount() >= 15){
// Will show Load More Button
}
Put the Button in a layout XML File. Inflate it, then:
if (c.getCount() > 15) {
btnLoadMore.setVisibility(View.INVISIBLE);
}
If you want the Button to be invisible.
Related
I have created a private member of the whole class called Member curMbr;
The activity (rather the fragment, since this is in a frament class) has a listview
with some contributions from members.
I also have a context menu on that list. When clicking on a contribution, I want a (customized) dialog box to show details about the member. (Member ID is part of the contribution objet. )
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
Log.d("FRGCOTIZ02", "create ctxt menu");
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
String[] menuItems = getResources().getStringArray(R.array.ar_menu_ctxt_participant);
// Get selected member
Contribution curCotis = (Contribution) (((ListView)v).getItemAtPosition(info.position));
Participant p = new Participant(helper.getDBItem(DBHelper.TABLE_PARTICIPANT,
DBHelper.COL_ID, curCotis.getParticipant()));
curMbr = new Member(helper.getDBItem(DBHelper.TABLE_MEMBER, DBHelper.COL_ID, p.getMember()));
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
Log.d("FRGCOTIZ01", curMbr.getId_());
}
#Override
public boolean onContextItemSelected(MenuItem item) {
return ( applyContextMenuSelection(item) || super.onContextItemSelected(item) );
}
private boolean applyContextMenuSelection(MenuItem item) {
switch (item.getItemId()) {
case 0: // Summary
final Dialog dlg = new Dialog(this.getContext());
final String sessID;
try {
sessID = KUtil.DATE_FORMAT.format(curSess.getDate());
dlg.setContentView(R.layout.alert_show_charges);
Button btnOK = dlg.findViewById(R.id.btn_alertOK);
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setupAlertDialogCharges(dlg, sessID, curMbr.getId_());
}
});
Button btnCancel = dlg.findViewById(R.id.btn_alertCancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dlg.dismiss();
}
});
dlg.show();
} catch (Exception e){
Log.d("FRAGMENT Contribution", e.getMessage());
}
break;
case 1: // Collect
break;
case 2: // Cancel
break;
default:
break;
}
return true;
}
In method onCreateContextMenu, I can get the member and display his ID.
But in method applyContextMenuSelection, there is an exception, saying the meber is null!
Funny enough there is another variable that I am using in that method, and it works fine. Difference is, that variable has been set at creation of the fragment.
How do I solve this?
I have been studying the code for a while and the only thing I could figure was that the issue is somehow linked to the use of contextmenu. It seems to me that variables are set back to their original when the menu action is supposed to be executed. Again, I am not too sure about that.
So, the only solution I found so far was to keep that vale in a "higher" context:
When I can still read the value,
getActivity().getIntent().putExtra(HomeActivity.ID_ENTRY, curMbr.getId_());
When I want to use it,
final String mbrID = getActivity().getIntent().getStringExtra(HomeActivity.ID_ENTRY);
I have 1 button in activity. i want to use this 1 button for multiple task.
So how can i do ?
If i pressed 1st time this button then it's change 2 button
if i pressed 2nd time then it's update my data
but it's only work 1st time 2nd time it's not work
see my code what i tried
Intent extras = getIntent();
{
if (extras.hasExtra("edit")) {
if (extras.getStringExtra("edit").equals("home")) {
etCompanyName.setEnabled(false);
etWebsite.setEnabled(false);
etEmail.setEnabled(false);
etPhoneHome.setEnabled(false);
etPhonePrimary.setEnabled(false);
etAddressLine1.setEnabled(false);
etAddressLine2.setEnabled(false);
etCity.setEnabled(false);
spStates.setEnabled(false);
etZip.setEnabled(false);
spContries.setEnabled(false);
//1st time use hear
txtSave.setText(getResources().getString(R.string.label_edit));
txtClose.setText(getResources().getString(R.string.label_back));
txtSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtSave.setText(getResources().getString(R.string.label_add));
txtClose.setText(getResources().getString(R.string.label_cancel));
etCompanyName.setEnabled(true);
etWebsite.setEnabled(true);
etEmail.setEnabled(true);
etPhoneHome.setEnabled(true);
etPhonePrimary.setEnabled(true);
etAddressLine1.setEnabled(true);
etAddressLine2.setEnabled(true);
etCity.setEnabled(true);
spStates.setEnabled(true);
etZip.setEnabled(true);
spContries.setEnabled(true);
}
});
if (extras != null) {
Company value = (Company) extras.getSerializableExtra("company");
etCompanyName.setText(value.getName());
etWebsite.setText(value.getWebsite());
etEmail.setText(value.getEmail());
etPhoneHome.setText(value.getPhoneHome());
etPhonePrimary.setText(value.getPhonePrimary());
etAddressLine1.setText(value.getAddressLine1());
etAddressLine2.setText(value.getAddressLine2());
etCity.setText(value.getCity());
etZip.setText(value.getZipcode());
}
} else {
//2nd time use hear
txtSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Company company = new Company();
company.setName(etCompanyName.getText().toString().trim());
company.setWebsite(etWebsite.getText().toString().trim());
company.setEmail(etEmail.getText().toString().trim());
company.setPhoneHome(etPhoneHome.getText().toString().trim());
company.setPhonePrimary(etPhonePrimary.getText().toString().trim());
company.setAddressLine1(etAddressLine1.getText().toString().trim());
company.setAddressLine2(etAddressLine2.getText().toString().trim());
company.setZipcode(etZip.getText().toString().trim());
company.setCity(etCity.getText().toString().trim());
company.setState(spStates.getSelectedItem().toString());
company.setCountry(spContries.getSelectedItem().toString());
company.setDate(Util.getInstance(AddCompanyActivity.this).getCurrentDate());
long isUpdated = myDb.updateCompany(company);
if (isUpdated != -1) {
Toast.makeText(getApplicationContext(), "Company Update Successfully: " + isUpdated, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Something wrong", Toast.LENGTH_SHORT).show();
}
finish();
}
});
}
}
}
You can see my above code i can used txtSave button for perform 2 task but it's only change two buttons and i'll change data and click on button then it's can't perform
Try this way, first declare global variable on your activity class file like below :
int count = 0;
After that add your click listener like that:
yourButton.setOnClickListener(v -> {
if (count == 0) { // the first click
count++;
// do your stuff
}else { // the second click
count = 0; // initialize the count to limit the button click just for the first and the second time only
// do your stuff
}
});
You should not create multiple OnClickListener for Button , Create only 1 and use it
example:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(btn.getText().equals("1")){
//perform action for 1
btn.setText("2");
//change button1 to button2
}else if(btn.getText().equals("2")){
//perform action for 2
btn.setText("3");
}
}
});
you could use single onclicklistener with switch case
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
swtich(extras.getStringExtra().toLowerCase(){
case "1":
// do something
break;
case "2":
// do something else
break;
}
});
}
Hi I'm working at my first bigger app in android studio "FlashCards". I would like it to work so after you click on the button the flashcard's textview changes its text to next random flashcard untill you see all of the them how can i do something like 'continue' to my loop from inside onClick method.
here's the loop's code:
while(i < mTestDeck.size()) {
// generates random number which will represent position in deck.
int random = randomGenerator.nextInt() % mTestDeck.size();
// if random flashcard was already shown create random number again
if (mTestDeck.get(random).wasShown())
continue;
//text view that we will operate on
TextView deckTextView = (TextView) findViewById(R.id.flashcard_text_view);
// set text
deckTextView.setText(mTestDeck.get(random).getFront());
// set mWasShown to true
mTestDeck.get(random).flashcardShown();
Button myButton = (Button) findViewById(R.id.know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mTestDeck.correctAnswer();
}
});
myButton = (Button) findViewById(R.id.dont_know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
First, this way, you have a potential infinite loop. And if it can happens, it will happens! It's not a good idea to "get random item and check if it's ok or try again".
I think that it's better to keep a list with all items in a random order. You just have to iterate over it.
Something like:
int currentPosition = 0;
List<Card> items = new ArrayList<Card>(mTestDeck).shuffle();
// Call this method once in onCreate or anywhere you initialize the UI
private void function setCurrentCard() {
Card currentItem = items.get(currentPosition);
[...] // Set all UI views here
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (currentPosition > items.size) {
// TODO? End?
return;
}
currentPosition++;
setCurrentCard();
}
});
}
I have three checkboxes and if any two of them are selected I want to disable the third checkbox immediately. I am not getting how to proceed.
Manage your CheckBoxes in a List, so you can iterate over them.
List<CheckBox> boxes = new ArrayList<>();
Assign them like so (in onCreate() of your activity)
boxes.add((CheckBox) findViewById(R.id.checkbox1));
boxes.add((CheckBox) findViewById(R.id.checkbox2));
boxes.add((CheckBox) findViewById(R.id.checkbox3));
Add an onCheckedChangeListener like this:
for(CheckBox box : boxes){
box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
manageBoxes();
}
});
}
and finally your manageBoxes()
private void manageBoxes(){
int count = 0;
for(CheckBox box : boxes){
count += box.isChecked()?1:0;
}
if(count>=2){
for(CheckBox box : boxes){
box.setEnabled(box.isChecked());
box.setClickable(box.isChecked()); // not sure if needed
}
}else{
// reset all boxes
for(CheckBox box : boxes){
box.setEnabled(true);
box.setClickable(true);
}
}
}
Just a quick and dirty thought. Hope this works.
Plus: This is scalable, so you could include some more checkboxes if needed.
Try to implement this way :
private ArrayList<Integer> integers = null;
integers = new ArrayList<>();
chkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
int position = (int) yourview.getTag();
if (chkBox.isChecked()) {
integers.add(position);
chkBox.setChecked(true);
} else {
if (integers.size() > 0) {
for (int i=0; i<integers.size(); i++) {
if (integers.get(i) == position) {
integers.remove(i);
}
}
});
if (integers.size() > 2) {
//Disable your third checkbox
}
Add a change handler or a click handler on each of the checkboxes and let it call a small method that is responsible for checking the value of each checkbox: if two of them are true disable the third one.
For example:
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
handleCheckBoxes();
}
});
//Do this for all the checkboxes
private void handleCheckBoxes(){
int checkedCount = 0;
CheckBox uncheckedBox = null;
if(checkBox1.isChecked()){
checkedCount++;
}
else{
uncheckedBox = checkBox1;
}
if(checkBox2.isChecked()){
checkedCount++;
}
else{
uncheckedBox = checkBox2;
}
if(checkBox3.isChecked()){
checkedCount++;
}
else{
uncheckedBox = checkBox3;
}
if(checkedCount == 2){
uncheckedBox .setEnabled(false);
}
else{
//enable all checkboxes
checkBox1.setEnables(true);
checkBox2.setEnables(true);
checkBox3.setEnables(true);
}
In pseudo code this would be:
Create variable to hold the number of checkboxes checked, let's call it amountChecked
When a checkbox gets checked => increment the amountChecked
When a checkbox gets checked => check if the amountChecked is equal or greater than the allowedAmountChecked (in your case this is 2)
=> if it is greater or equal to the allowedAmountChecked then disable the remaining checkboxes
Do you need to inflate a view in order to get its id for the onClick method? Because when I run my program in the emulator and click on the specific button it does nothing! I want it to go back to the main.xml layout! Do I need to procces the onClick some other way?
public void onClick(View v) {
switch( v.getId()){
case R.id.play:
setContentView(R.layout.play);
setQuestion();
break;
case R.id.level:
setContentView(R.layout.level);
if(lvl.equals("1")) {
lvl1.setChecked(true);
}
if(lvl.equals("2")) {
lvl2.setChecked(true);
}
if(lvl.equals("3")) {
lvl3.setChecked(true);
}
if(lvl.equals("4")) {
lvl4.setChecked(true);
}
if(lvl.equals("5")) {
lvl5.setChecked(true);
}
break;
case R.id.setLevel:
if(lvl1.isChecked()) {
setLevel("1");
}
if(lvl2.isChecked()) {
setLevel("2");
}
if(lvl3.isChecked()) {
setLevel("3");
}
if(lvl4.isChecked()) {
setLevel("4");
}
if(lvl5.isChecked()) {
setLevel("5");
}
setContentView(R.layout.main);
break;
}
}
Here is how I get the views:
setContentView(R.layout.main);
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(this);
Button level = (Button)findViewById(R.id.level);
level.setOnClickListener(this);
Button setLevel = (Button)getLayoutInflater().inflate(R.layout.level, null).findViewById(R.id.setLevel);
setLevel.setOnClickListener(this);
lvl1 = (RadioButton)getLayoutInflater().inflate(R.layout.level, null).findViewById(R.id.lvl1);
lvl2 = (RadioButton)getLayoutInflater().inflate(R.layout.level, null).findViewById(R.id.lvl2);
lvl3 = (RadioButton)getLayoutInflater().inflate(R.layout.level, null).findViewById(R.id.lvl3);
lvl4 = (RadioButton)getLayoutInflater().inflate(R.layout.level, null).findViewById(R.id.lvl4);
lvl5 = (RadioButton)getLayoutInflater().inflate(R.layout.level, null).findViewById(R.id.lvl5);
What should I do so that when I click the setLevel button it changes the view back to the main.xml view
Andrew,
You may want to make individual onClick() methods for each item. That's how I handle my click-able objects.
Example:
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//perform play button actions here
}
});
This way you already have the button object created based on its ID value, and the onClickListener is specifically tailored to that item.
good luck!