Кнопки Android Hide and Show для Android от состояния

моему приложению Android нужна функция, у которой есть кнопка, которая должна отображаться и скрываться на основе одного TextView. Вот мой код и плохо объясняю далее.

public class currentCar extends Fragment implements AsyncResponse, AdapterView.OnItemClickListener {
final String TAG = this.getClass().getName();
private ArrayList<AcceptCars> carList;
private ListView lvCurrent;
private FunDapter<AcceptCars> adapter;
SharedPreferences pref;

public currentCar() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v =  inflater.inflate(R.layout.fragment_current_car, container, false);

    ImageLoader.getInstance().init(UILConfig.config(getActivity()));

    lvCurrent = (ListView) v.findViewById(R.id.lvCurrent);

    pref = getActivity().getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
    Log.d(TAG, pref.getString("username",""));

    PostResponseAsyncTask taskRead = new PostResponseAsyncTask(getActivity(), this);

    taskRead.execute("http://carkila.esy.es/carkila/current.php?acceptCarOwner="+pref.getString("username",""));

    return v;
}

@Override
public void processFinish(String s) {
    carList = new JsonConverter<AcceptCars>().toArrayList(s, AcceptCars.class);

    BindDictionary<AcceptCars> dict = new BindDictionary<AcceptCars>();

    dict.addDynamicImageField(R.id.ivImg1, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return item.acceptImage;
        }
    }, new DynamicImageLoader() {
        @Override
        public void loadImage(String url, ImageView view) {

            ImageLoader.getInstance().displayImage(url, view);
        }
    });
    dict.addStringField(R.id.tvCarModel, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Car Model: " + item.acceptModel;
        }
    });
    dict.addStringField(R.id.tvResDate, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Date: " + item.acceptDate;
        }
    });
    dict.addStringField(R.id.tvResTime, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Time: " + item.acceptTime;
        }
    });
    dict.addStringField(R.id.tvResLocation, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Location: " + item.acceptResLocation;
        }
    });
    dict.addStringField(R.id.tvCarType, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Car Type: " + item.acceptType;
        }
    });
    dict.addStringField(R.id.tvCapacity, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Capacity: " + item.acceptCapacity;
        }
    });
    dict.addStringField(R.id.tvFuelType, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Fuel Type: " + item.acceptFuelType;
        }
    });
    dict.addStringField(R.id.tvPlateNumber, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Plate Number: " + item.acceptPlateNumber;
        }
    });
    dict.addStringField(R.id.tvPoster, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Posted by : " + item.acceptCarOwner;
        }
    });
    dict.addStringField(R.id.tvRenter, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Rented by: "+ item.renters;
        }
    });
    dict.addStringField(R.id.tvDestination, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Destination: " + item.acceptDestination;
        }
    });

    dict.addStringField(R.id.tvResPrice, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Destination: " + item.acceptPrice;
        }
    });
    dict.addStringField(R.id.tvresID, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return ""+ item.acceptedID;
        }
    });
    dict.addStringField(R.id.tvstatus, new StringExtractor<AcceptCars>() {
        @Override
        public String getStringValue(AcceptCars item, int position) {
            return "Status: "+ item.payment;
        }
    });

    adapter = new FunDapter<>(
            getActivity(), carList, R.layout.layout_rented, dict);
    lvCurrent.setAdapter(adapter);
    lvCurrent.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    AcceptCars selectedCars = carList.get(i);
        Intent in = new Intent(getActivity(), ownerStatus.class);
        in.putExtra("cars", selectedCars);
        startActivity(in);
}
}

В начале этого listView item.payment является "неоплаченным", и он перейдет к ownerStatus.class

OwnerStatus.class

public class ownerStatus extends AppCompatActivity {
TextView tvStatus, tvPaymentStatus, tvresID, tvCarModel, tvCarType, tvCapacity, tvFuelType, tvPlateNumber, tvResDate, tvResTime, tvResLocation, tvPoster, tvRenter, tvDestination, tvPrice;
ImageView ivImage;
Button btnPaid;
Button btnDone;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_owner_status);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    onButtonClick();

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    final AcceptCars Cars = (AcceptCars) getIntent().getSerializableExtra("cars");
    ImageLoader.getInstance().init(UILConfig.config(ownerStatus.this));
    tvCarModel = (TextView) findViewById(R.id.tvCarModel);
    tvCarType = (TextView) findViewById(R.id.tvCarType);
    tvCapacity = (TextView) findViewById(R.id.tvCapacity);
    tvFuelType = (TextView) findViewById(R.id.tvFuelType);
    tvPoster = (TextView) findViewById(R.id.tvPoster);
    tvPlateNumber = (TextView) findViewById(R.id.tvPlateNumber);
    tvResDate = (TextView) findViewById(R.id.tvResDate);
    tvResTime = (TextView) findViewById(R.id.tvResTime);
    tvResLocation = (TextView) findViewById(R.id.tvResLocation);
    tvPrice = (TextView) findViewById(R.id.tvPrice);
    tvDestination = (TextView) findViewById(R.id.tvDestination);
    tvRenter = (TextView) findViewById(R.id.tvRenter);
    tvresID = (TextView) findViewById(R.id.tvresID);
    tvPaymentStatus = (TextView) findViewById(R.id.tvPaymentStatus);
    tvStatus = (TextView) findViewById(R.id.tvStatus);
    ivImage = (ImageView) findViewById(R.id.ivImg1);

    if (Cars != null) {
        tvresID.setText("" + Cars.acceptedID);
        tvCarModel.setText(Cars.acceptModel);
        tvCarType.setText(Cars.acceptType);
        tvCapacity.setText(Cars.acceptCapacity);
        tvFuelType.setText(Cars.acceptFuelType);
        tvPlateNumber.setText(Cars.acceptPlateNumber);
        tvResDate.setText(Cars.acceptDate);
        tvResTime.setText(Cars.acceptTime);
        tvResLocation.setText(Cars.acceptResLocation);
        tvPoster.setText(Cars.acceptCarOwner);
        tvRenter.setText(Cars.renters);
        tvDestination.setText(Cars.acceptDestination);
        tvPrice.setText(Cars.acceptPrice);
        tvPaymentStatus.setText(Cars.payment);
        tvStatus.setText(Cars.payment);

        ImageLoader.getInstance().displayImage(Cars.acceptImage, ivImage);
    }

}

public void onButtonClick() {
    btnPaid = (Button) findViewById(R.id.btnPaid);
    btnPaid.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder a_paid = new AlertDialog.Builder(ownerStatus.this);
            a_paid.setMessage("Does the renter paid the transaction?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            HashMap postData = new HashMap();
                            postData.put("acceptID", tvresID.getText().toString());
                            postData.put("payment", "paid");
                            PostResponseAsyncTask taskPaid = new PostResponseAsyncTask(ownerStatus.this, postData, false, new AsyncResponse() {
                                @Override
                                public void processFinish(String s) {
                                    if (s.contains("success")) {
                                        Toast.makeText(ownerStatus.this, "renter is paid", Toast.LENGTH_SHORT).show();
                                        Intent in = new Intent(ownerStatus.this, OwnerTabs.class);
                                        startActivity(in);
                                        finish();
                                    } else {
                                        Toast.makeText(getApplicationContext(), "Failed. Zzzz ☻", Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                            taskPaid.execute("http://carkila.esy.es/carkila/paid.php");
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.cancel();
                        }
                    });
            AlertDialog alert = a_paid.create();
            alert.setTitle("Payment");
            alert.show();
        }
    });
    //===================================================================================//
    btnDone = (Button) findViewById(R.id.btnDone);
    btnDone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder a_done = new AlertDialog.Builder(ownerStatus.this);
            a_done.setMessage("Is the rent is done?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            HashMap postData2 = new HashMap();
                            postData2.put("acceptID", tvresID.getText().toString());
                            postData2.put("status", "done");
                            PostResponseAsyncTask task1 = new PostResponseAsyncTask(ownerStatus.this, postData2, new AsyncResponse() {
                                @Override
                                public void processFinish(String s) {
                                    if (s.contains("success")) {
                                        Toast.makeText(ownerStatus.this, "renter is paid", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(getApplicationContext(), "Failed. Zzzz ☻", Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                            task1.execute("http://carkila.esy.es/carkila/done.php");
                                }
                            })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.cancel();
                        }
                    });
            AlertDialog alert = a_done.create();
            alert.setTitle("Done");
            alert.show();
        }
    });
}
}

И здесь. Когда Cars.payment неоплачивается, btnPaid отобразит и скроет btnDone, но когда Cars.payment будет оплачено, btnPaid скроется, а btnDone теперь будет Спрятать. Надеюсь, вы понимаете, как я объяснил и помог мне с моей проблемой. Спасибо, сэр:)

Ответ 1

Из ваших комментариев, вы говорите, что вам нужно проверить:

if(Cars.payment) {
    btnDone.setVisibility(View.GONE);
    btnPaid.setVisibility(View.VISIBLE);
 } else {
    btnPaid.setVisibility(View.GONE);
    btnDone.setVisibility(View.VISIBLE);
 }

Ответ 2

btnDone.setVisibility(someCondition? View.GONE : View.VISIBLE);
btnPaid.setVisibility(!someCondition? View.GONE : View.VISIBLE);

Ответ 3

вы передаете выбранный автомобиль в намерении и попадете в OwnerStatus.class. Поэтому, когда вы устанавливаете значения из выбранного автомобиля, вы просто проверяете car.payment и устанавливаете видимость кнопки имени статуса.

Пример: -

вам нужно объявить кнопку перед этим кодом, как показано ниже: -

 btnPaid = (Button) findViewById(R.id.btnPaid);
 btnDone = (Button) findViewById(R.id.btnDone);


if (Cars != null) {
        tvresID.setText("" + Cars.acceptedID);
        tvCarModel.setText(Cars.acceptModel);
        tvCarType.setText(Cars.acceptType);
        tvCapacity.setText(Cars.acceptCapacity);
        tvFuelType.setText(Cars.acceptFuelType);
        tvPlateNumber.setText(Cars.acceptPlateNumber);
        tvResDate.setText(Cars.acceptDate);
        tvResTime.setText(Cars.acceptTime);
        tvResLocation.setText(Cars.acceptResLocation);
        tvPoster.setText(Cars.acceptCarOwner);
        tvRenter.setText(Cars.renters);
        tvDestination.setText(Cars.acceptDestination);
        tvPrice.setText(Cars.acceptPrice);
        tvPaymentStatus.setText(Cars.payment);
        tvStatus.setText(Cars.payment);

        ImageLoader.getInstance().displayImage(Cars.acceptImage, ivImage);

       //here you just check the status of the car payment

       if(Car.payment.equalsignorecase("unpaid"))
      {
       btnDone.setVisibility(View.Gone);
       btnPaid.setVisibility(View.VISIBLE);
      }
      else
      {
      // what you want to do here
      }


    }