Ваша программа не знает, какую точность использовать десятичные числа, чтобы она выдавала:
java.lang.ArithmeticException: Non-terminating decimal expansion
MathContext precision = new MathContext(int setPrecisionYouWant); // example 2
BigDecimal a = new BigDecimal("1.6",precision);
BigDecimal b = new BigDecimal("9.2",precision);
a.divide(b) // result = 0.17
Вы можете установить событие onClick
в свой метод getView
вашего пользовательского адаптера .. проверьте ссылку http://androidforbeginners.blogspot.it/2010/03/clicking-buttons-in-listviewrow .html
ДЛЯ ПОЛЬЗОВАТЕЛЕЙ KOTLIN
внутри вашего метода getView (...), если вы попытаетесь запустить действие с помощью кнопки onClickListener:
myButton.setOnClickListener{
val intent = Intent(this@CurrentActivity, SecondActivity::class.java)
startActivity(intent)
}
Передайте правильный указатель для «this «
В методе getview выставлять слушателя вне проверки просмотра. Попробуйте это сделать .. он работал в моем случае .. Как увеличить или уменьшить значение edittext в каждой строке списка?
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.vehicals_details_row, parent, false);
Button deleteImageView = (Button) row.findViewById(R.id.DeleteImageView);
deleteImageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//...
}
});
}
Но вы можете получить проблему - listView строка не кликабельна . Решение:
android:focusable="true"
android:focusable="false"
ListView
focusable и Button
нефокусируемым? Я имею в виду, что происходит, когда мы это делаем?
– Bugs Happen
21 August 2015 в 06:48
В вашем пользовательском адаптере внутри метода getView:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Do things Here
}
});
Я нахожу, что
final Button yourButton = (Button)view.findViewById(R.id.your_button);
yourButton.setFocusable(false);
yourButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
...///);
может решить проблему. Если вы хотите получить некоторые данные при нажатии кнопки, полезно использовать теги. Здесь кнопка объявляется окончательной, потому что она будет использоваться внутри внутреннего класса.
Попробуйте это,
public View getView(final int position, View convertView,ViewGroup parent)
{
if(convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = (LinearLayout)inflater.inflate(R.layout.YOUR_LAYOUT, null);
}
Button Button1= (Button) convertView .findViewById(R.id.BUTTON1_ID);
Button1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// Your code that you want to execute on this button click
}
});
return convertView ;
}
Это может помочь вам ....
Я предполагаю, что вы определили пользовательский адаптер для вашего ListView.
Если это так, вы можете назначить onClickListener
для вашей кнопки внутри метода getView()
пользовательского адаптера.
Это обсуждалось во многих сообщениях, но все же я не мог найти решение с помощью:
android:focusable="false"
android:focusableInTouchMode="false"
android:focusableInTouchMode="false"
Ниже решение будет работать с любой из компонентов ui: Button, ImageButtons, ImageView, Textview. LinearLayout, RelativeLayout кликает внутри ячейки списка и отвечает на onItemClick:
Класс адаптера - getview ():
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.my_ref_row, parent, false);
}
final Organization currentOrg = organizationlist.get(position).getOrganization();
TextView name = (TextView) view.findViewById(R.id.name);
Button btn = (Button) view.findViewById(R.id.btn_check);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
context.doSelection(currentOrg);
}
});
if(currentOrg.isSelected()){
btn.setBackgroundResource(R.drawable.sub_search_tick);
}else{
btn.setBackgroundResource(R.drawable.sub_search_tick_box);
}
}
В этом вы можете получить объект с нажатой кнопкой активность. (Специально, если вы хотите, чтобы кнопка выступала в качестве флажка с выбранными и не выбранными состояниями):
public void doSelection(Organization currentOrg) {
Log.e("Btn clicked ", currentOrg.getOrgName());
if (currentOrg.isSelected() == false) {
currentOrg.setSelected(true);
} else {
currentOrg.setSelected(false);
}
adapter.notifyDataSetChanged();
}
Класс для ArrayList & amp; ArrayAdapter
class RequestClass {
private String Id;
private String BookingTime;
private String UserName;
private String Rating;
public RequestClass(String Id,String bookingTime,String userName,String rating){
this.Id=Id;
this.BookingTime=bookingTime;
this.UserName=userName;
this.Rating=rating;
}
public String getId(){return Id; }
public String getBookingTime(){return BookingTime; }
public String getUserName(){return UserName; }
public String getRating(){return Rating; }
}
Основная активность:
ArrayList<RequestClass> _requestList;
_requestList=new ArrayList<>();
try {
JSONObject jsonobject = new JSONObject(result);
JSONArray JO = jsonobject.getJSONArray("Record");
JSONObject object;
for (int i = 0; i < JO.length(); i++) {
object = (JSONObject) JO.get(i);
_requestList.add(new RequestClass( object.optString("playerID"),object.optString("booking_time"),
object.optString("username"),object.optString("rate") ));
}//end of for loop
RequestCustomAdapter adapter = new RequestCustomAdapter(context, R.layout.requestlayout, _requestList);
listView.setAdapter(adapter);
Пользовательский класс адаптера
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by wajid on 1/12/2018.
*/
class RequestCustomAdapter extends ArrayAdapter<RequestClass> {
Context mContext;
int mResource;
public RequestCustomAdapter(Context context, int resource,ArrayList<RequestClass> objects) {
super(context, resource, objects);
mContext=context;
mResource=resource;
}
public static class ViewHolder{
RelativeLayout _layout;
TextView _bookingTime;
TextView _ratingTextView;
TextView _userNameTextView;
Button acceptButton;
Button _rejectButton;
}
@NonNull
@Override
public View getView(final int position, View convertView, ViewGroup parent){
final ViewHolder holder;
if(convertView == null) {
LayoutInflater inflater=LayoutInflater.from(mContext);
convertView=inflater.inflate(mResource,parent,false);
holder=new ViewHolder();
holder._layout = convertView.findViewById(R.id.requestLayout);
holder._bookingTime = convertView.findViewById(R.id.bookingTime);
holder._userNameTextView = convertView.findViewById(R.id.userName);
holder._ratingTextView = convertView.findViewById(R.id.rating);
holder.acceptButton = convertView.findViewById(R.id.AcceptRequestButton);
holder._rejectButton = convertView.findViewById(R.id.RejectRequestButton);
holder._rejectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mContext, holder._rejectButton.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
holder.acceptButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mContext, holder.acceptButton.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
convertView.setTag(holder);
}
else{
holder=(ViewHolder)convertView.getTag();
}
holder._bookingTime.setText(getItem(position).getBookingTime());
if(!getItem(position).getUserName().equals("")){
holder._userNameTextView.setText(getItem(position).getUserName());
}
if(!getItem(position).getRating().equals("")){
holder._ratingTextView.setText(getItem(position).getRating());
}
return convertView;
}
}
ListView в главном xml:
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:id="@+id/AllRequestListView">
</ListView>
Макет ресурса для просмотра списка requestlayout.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/requestLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bookingTime"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/bookingTime"
android:text="Temp Name"
android:id="@+id/userName"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/userName"
android:text="No Rating"
android:id="@+id/rating"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/AcceptRequestButton"
android:focusable="false"
android:layout_below="@+id/rating"
android:text="Accept"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/RejectRequestButton"
android:layout_below="@+id/AcceptRequestButton"
android:focusable="false"
android:text="Reject"
/>
</RelativeLayout>