Im new in android programing, I want make calculating with multiple spinner that have value string and edit text. and proccess with button click and show on text view. please healp me to fix so i can learn next subject.
THx
My activity .java code:
public class MainActivity extends Activity {
private EditText jumlah;
String[] spinnerValues = { "Bakso", "Es Buah" };
String[] spinnerSubs = {"10000", "8000" };
int total_images[] = { R.drawable.bakso, R.drawable.es_buah };
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner mySpinner = (Spinner) findViewById(R.id.spinner_show);
mySpinner.setAdapter(new MyAdapter(this, R.layout.menu_resto,
spinnerValues));
jumlah = (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
initButton();
}
private void initButton() {
button1.setOnClickListener(new OnClickListener() {
// this one performs an action when our button is clicked. it performs whatever is below
#Override
public void onClick(View v) {
// String strA = i want call the spinersubs value that chsoed. how ?
String strB = jumlah.getText().toString();
Double dblAnswer = doCalc(strA, strB);
TextView lblAnswer = (TextView) findViewById(R.id.lblAnswer);
// the disadvantage is that we can't do anything to it outside of this curly
// in general it's wasteful to use fields when you can suffice with local variable
String answer = String.valueOf(dblAnswer);
// we get our answer and turn it to a string.
lblAnswer.setText(answer);
// finally we set our result to the textView.
}
});
}
public double doCalc(String a, String b) {
double dblA = Double.parseDouble(a);
double dblB = Double.parseDouble(b);
return dblA * dblB;
}
class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context ctx, int txtViewResourceId, String[] objects) {
super(ctx, txtViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View cnvtView, ViewGroup prnt) {
return getCustomView(position, cnvtView, prnt);
}
#Override
public View getView(int pos, View cnvtView, ViewGroup prnt) {
return getCustomView(pos, cnvtView, prnt);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View mySpinner = inflater.inflate(R.layout.menu_resto, parent,
false);
TextView main_text = (TextView) mySpinner
.findViewById(R.id.text_main_seen);
main_text.setText(spinnerValues[position]);
TextView subSpinner = (TextView) mySpinner
.findViewById(R.id.sub_text_seen);
subSpinner.setText(spinnerSubs[position]);
ImageView left_icon = (ImageView) mySpinner
.findViewById(R.id.left_pic);
left_icon.setImageResource(total_images[position]);
return mySpinner;
}
Here my XML
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="X - Resto Menu"
android:textSize="30px" />
<Spinner
android:id="#+id/spinner_show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100px"
android:drawSelectorOnTop="true" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_show"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:ems="10" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_show"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:text="Jumlah Pesanan" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:onClick="#string/hitung"
android:text="#string/pesan" />
<TextView
android:id="#+id/lblAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text="" />
You need to implement CustomOnItemSelectedListener for Spinner like
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
and then set this Listener to your Spinner like
mySpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
and in Button click you'll get a Spinner selected value like
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyAndroidAppActivity.this,
"OnClickListener : " +
"\nSpinner : "+ String.valueOf(mySpinner.getSelectedItem())
,Toast.LENGTH_SHORT).show();
}
});
Go to this for Tutorial
Related
I am a newbie programmer in android.I am trying to develop a simple paternity blood test.The logic is like this.I have three spinners and blood group A,B,AB and O will be listed into the spinner.The user have to chose blood type from A,B,AB or O for child,mother and father and then click submit button.The button will do some matching and produce a string result.I have tried several methods whichI found on internet. But still unable to use button click function.
Here is my code.Plz correct my mistake .Thanks.
<?xml version="1.0" encoding="utf-8"?>
<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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_paternity"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:layout_marginTop="52dp"
android:id="#+id/paternity_ans" />
<TextView
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:id="#+id/textView6"
android:text="Father"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_width="100dp"
android:layout_above="#+id/childblds"
android:layout_centerHorizontal="true" />
<TextView
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="53dp"
android:id="#+id/textView5"
android:text="Child "
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_width="100dp"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/btn_paternity"
android:layout_toStartOf="#+id/btn_paternity" />
<Spinner
android:layout_width="100dp"
android:layout_height="wrap_content"
android:spinnerMode="dialog"
android:id="#+id/dadblds"
android:dropDownWidth="match_parent"
android:layout_toLeftOf="#+id/textView4"
android:layout_toStartOf="#+id/textView4"
android:layout_alignBottom="#+id/childblds"
android:layout_alignTop="#+id/childblds" />
<Spinner
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/childblds"
android:spinnerMode="dialog"
android:dropDownWidth="match_parent"
android:layout_marginTop="13dp"
android:layout_below="#+id/textView5"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
<Spinner
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/momblds"
android:spinnerMode="dialog"
android:entries="#array/paternitybldtype"
android:dropDownWidth="match_parent"
android:layout_alignTop="#+id/dadblds"
android:layout_alignLeft="#+id/textView4"
android:layout_alignStart="#+id/textView4" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_paternity"
android:layout_below="#+id/dadblds"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:gravity="center_horizontal"
android:text="Mother"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_width="100dp"
android:layout_marginLeft="9dp"
android:layout_marginStart="9dp"
android:layout_above="#+id/childblds"
android:layout_toRightOf="#+id/textView6"
android:layout_toEndOf="#+id/textView6" />
</RelativeLayout>
</LinearLayout>
Fragments code:
public class Paternitytest extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.paternitytestlo, container, false);
final Button setItem = (Button) view.findViewById(R.id.btn_paternity);
final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);
setItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Some if else statement will be applied here by using String c, f and m
}
});
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);
// Spinner Drop down elements
String[] categories = {"A", "B", "O", "AB",};
// Creating adapter for spinner
ArrayAdapter adapter = new ArrayAdapter(
getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);
// Drop down layout style - list view with radio button
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
childspinner.setAdapter(adapter);
dadspinner.setAdapter(adapter);
momspinner.setAdapter(adapter);
// Spinner click listener
childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String c = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String f = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String m = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
I have made some changes in your code so try this.
public class Paternitytest extends Fragment {
private String childSpinnerString, momSpinnerString, dadspinnerString;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.paternitytestlo,
container, false);
final Button setItem = (Button) view.findViewById(R.id.btn_paternity);
final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);
setItem.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//Some if else statement will be applied here by using String c, f and m
Log.d("Blood groups- ", "Child - " + childSpinnerString + " Mom - " + momSpinnerString + " Dad - " + dadspinnerString);
}
});
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);
// Spinner Drop down elements
String[] categories = {"A", "B", "O", "AB",};
// Creating adapter for spinner
ArrayAdapter adapter = new ArrayAdapter(
getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);
// Drop down layout style - list view with radio button
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
childspinner.setAdapter(adapter);
dadspinner.setAdapter(adapter);
momspinner.setAdapter(adapter);
// Spinner click listener
childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
childSpinnerString = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
dadspinnerString = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
momSpinnerString = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Try onClickListener for your button:
btn_paternity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String mom = momblds.getSelectedItem().toString();
}
});
I have created a custom ListView by extending LinearLayout for every row (Contact) and i need to select the item, but the method "setOnItemClickListener()" not working. I have just put a onItemSelectedListener under and now the method "setOnItemClickListener" select always the first item though i select other row
MainActivity:
public class MainActivity extends AppCompatActivity {
private ListView lvPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvPhone = (ListView)findViewById(R.id.listPhone);
final List<PhoneBook> listPhoneBook = new ArrayList<PhoneBook>();
listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(),R.drawable.image),"Contact_1","123456789","av1#gmail.com","1"));
listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(),R.drawable.image),"Contact_2","123456789","av2#gmail.com","2"));
listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(),R.drawable.image),"Contact_3","123456789","av3#gmail.com","3"));
final PhoneBookAdapter adapter = new PhoneBookAdapter(this, listPhoneBook);
lvPhone.setAdapter(adapter);
lvPhone.setItemsCanFocus(false);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog d = new Dialog(MainActivity.this);
d.setTitle("Login");
d.setCancelable(true);
d.setContentView(R.layout.account);
d.show();
Button button_close = (Button) d.findViewById(R.id.DCancel);
button_close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
d.dismiss();
}
});
Button button_login = (Button) d.findViewById(R.id.DLogin);
button_login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String mName = new String("Ciao");
String mPhone;
String mEmail;
String mID;
TextView TextName = (TextView) d.findViewById(R.id.DName);
TextView TextPhone = (TextView)d.findViewById(R.id.DPhone);
TextView TextEmail = (TextView)d.findViewById(R.id.DEmail);
TextView TextID = (TextView)d.findViewById(R.id.DID);
mName=TextName.getText().toString();
mPhone=TextPhone.getText().toString();
mEmail=TextEmail.getText().toString();
mID=TextID.getText().toString();
listPhoneBook.add(new PhoneBook(BitmapFactory.decodeResource(getResources(),R.drawable.image),mName,mPhone,mEmail,mID));
lvPhone.setAdapter(adapter);
d.dismiss();
}
});
}
});
lvPhone.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView TextName = (TextView) view.findViewById(R.id.tvName);
TextView TextPhone = (TextView)view.findViewById(R.id.tvPhone);
TextView TextEmail = (TextView)view.findViewById(R.id.tvEmail);
TextView TextID = (TextView)view.findViewById(R.id.tvID);
String tvName = new String(TextName.getText().toString());
String tvPhone = new String(TextPhone.getText().toString());
String tvEmail = new String(TextEmail.getText().toString());
String tvID = new String(TextID.getText().toString());
Toast.makeText(MainActivity.this, tvName, Toast.LENGTH_SHORT).show();
}
});
lvPhone.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
PhoneBookAdapter:
public class PhoneBookAdapter extends BaseAdapter{
private Context mContext;
private List<PhoneBook> mListPhoneBook;
public PhoneBookAdapter (Context context, List<PhoneBook> list) {
mContext = context;
mListPhoneBook = list;
}
#Override
public int getCount() {
return mListPhoneBook.size();
}
#Override
public Object getItem(int position) {
return mListPhoneBook.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
PhoneBook entry = mListPhoneBook.get(position);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.phonebook_row,null);
}
ImageView ivAvatar = (ImageView)convertView.findViewById(R.id.imgAvatar);
ivAvatar.setImageBitmap(entry.getmAvatar());
TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
tvName.setText(entry.getmName());
TextView tvPhone = (TextView)convertView.findViewById(R.id.tvPhone);
tvPhone.setText(entry.getmPhone());
TextView tvEmail = (TextView)convertView.findViewById(R.id.tvEmail);
tvEmail.setText(entry.getmEmail());
TextView tvID = (TextView)convertView.findViewById(R.id.tvID);
tvID.setText(entry.getmID());
return convertView;
}
}
`
PhoneBook_row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true">
<ImageView
android:id="#+id/imgAvatar"
android:layout_width="70dp"
android:layout_height="70dp"
android:scaleType="fitCenter"
android:src="#drawable/image"
android:clickable="true"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:clickable="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvName"
android:textStyle="bold"
android:clickable="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvPhone"
android:textStyle="bold"
android:clickable="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvEmail"
android:textStyle="bold"
android:clickable="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvID"
android:textStyle="bold"
android:clickable="true"/>
</LinearLayout>
</LinearLayout>
Replace your PhoneBook_row.xml with the one I am putting up here, I have tried this and it worked for me. I have changed all your android:clickable="true" to android:clickable="false". The reason for doing this is, all of your child views consume click and the result is your parent view i.e ListView not getting the click event. Hope this helps.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false">
<ImageView
android:id="#+id/imgAvatar"
android:layout_width="70dp"
android:layout_height="70dp"
android:scaleType="fitCenter"
android:src="#drawable/image"
android:clickable="false"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:clickable="false">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvName"
android:textStyle="bold"
android:clickable="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvPhone"
android:textStyle="bold"
android:clickable="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvEmail"
android:textStyle="bold"
android:clickable="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvID"
android:textStyle="bold"
android:clickable="false"/>
</LinearLayout>
</LinearLayout>
Looks like you are missing the override.
Add an #Override before the function as shown below.
lvPhone.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
Also adding android:clickable = true in the layout file wouldn't be necessary.
You have changed your question , anyway i believe you can now get the item selected listener working. To get the item which is selected you can use the position as below
lvPhone.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PhoneBook phoneBook = listPhoneBook.get(position);
Toast.makeText(MainActivity.this, phoneBook.getName() , Toast.LENGTH_SHORT).show();
//where getName is a function to get the name in the phonebook class
}
});
I've read some SO questions like this and this but still couldn't figure out whats wrong with my code.
I have a ListFragment, and each row has a TextView and a CheckBox.
Clicking the CheckBox is working, but clicking on the TextView does nothing, and OnListItemClick doesn't get called. I've also tried to dynamically add an OnClickListener, which make it work, but it's not the correct way to do it, and it also lacks the GUI feedback of the click (item being "highlighted" for a sec).
This is my textview_with_checkbox.XML I'm using for each item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:gravity="left"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal" >
<TextView
android:id="#+id/textview_event_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="3dp"
android:paddingTop="5dp"
android:focusable="true"
android:singleLine="false" />
<CheckBox
android:id="#+id/checkbox_for_event_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.05"
android:focusable="false"
android:clickable="false" />
</LinearLayout>
now the code:
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
displayEventsLogFiles();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
String chosenItem = (String) getListAdapter().getItem(position);
mCallBack.onEventItemSelected(chosenItem);
}
static class myCustomAdapterViewHolder
{
public TextView eventName;
public CheckBox eventCheckBox;
}
private class myCustomAdapter extends ArrayAdapter<String>
{
private ArrayList<String> sortedList;
private Context m_oContext;
List<String> m_oValues = null;
public myCustomAdapter(Context cont, int viewResId, List<String> objects)
{
super(cont, viewResId, objects);
m_oContext = cont;
m_oValues = objects;
sortedList = new ArrayList<String>();
for (String str : objects)
sortedList.add(str);
java.util.Collections.sort(sortedList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View l_oRowView = convertView;
myCustomAdapterViewHolder l_oInitializedViewHolder = null;
final int l_nPosition = position;
// Use convertView if possible, otherwise inflate a view:
if (l_oRowView == null)
{
LayoutInflater inflater = (LayoutInflater) m_oContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
l_oRowView = inflater.inflate(R.layout.textview_with_checkbox, parent, false);
// PlaceHolder pattern:
final myCustomAdapterViewHolder l_oViewHolder = new myCustomAdapterViewHolder();
l_oViewHolder.eventName = (TextView) l_oRowView.findViewById(R.id.textview_event_name);
l_oViewHolder.eventCheckBox = (CheckBox) l_oRowView.findViewById(R.id.checkbox_for_event_name);
l_oViewHolder.eventCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox)v;
//cb.setChecked(!cb.isChecked());
String l_sFilename = l_oViewHolder.eventName.getText().toString();
if (cb.isChecked())
{
if (!m_lstSelectedFilenames.contains(l_sFilename))
m_lstSelectedFilenames.add(l_sFilename);
}
else
{
if (m_lstSelectedFilenames.contains(l_sFilename))
m_lstSelectedFilenames.remove(l_sFilename);
}
}
});
l_oViewHolder.eventCheckBox.setFocusable(false);
//l_oViewHolder.eventCheckBox.setClickable(false);
// "Add" the viewHolder as a tag:
l_oRowView.setTag(l_oViewHolder);
l_oInitializedViewHolder = l_oViewHolder;
}
else
l_oInitializedViewHolder = (myCustomAdapterViewHolder) l_oRowView.getTag();
// By now, the rowView is initialized, just get the viewHolder and then get the views from it, to update:
//myCustomAdapterViewHolder l_oViewHolder = (myCustomAdapterViewHolder) l_oRowView.getTag();
/*l_oInitializedViewHolder.eventName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallBack.onEventItemSelected((String)getListAdapter().getItem(l_nPosition));
}
});*/
l_oInitializedViewHolder.eventName.setText(m_oValues.get(position));
return l_oRowView;
//return super.getView();
}
public myCustomAdapter(Context cont, int viewResId, String[] strings)
{
this(cont, viewResId, Arrays.asList(strings));
}
#Override
public String getItem(int position)
{
return sortedList.get(position);
}
#Override
public int getPosition(String item)
{
return sortedList.indexOf(item);
}
}
What am I doing wrong here?
All I want is to be able to select "files" for deletion, using the CheckBoxes
Try only using only onclick for textview and checkbox, not onListItemClick -which you can remove- as well, so you should change some properties for the linear layout as well.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:focusable="false"
android:gravity="left"
android:orientation="horizontal" >
<TextView
android:id="#+id/textview_event_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="3dp"
android:paddingTop="5dp"
android:focusable="true"
android:singleLine="false" />
<CheckBox
android:id="#+id/checkbox_for_event_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.05"
android:focusable="false"
android:clickable="false" />
</LinearLayout>
Implement in the adapter
// PlaceHolder pattern:
final myCustomAdapterViewHolder l_oViewHolder = new myCustomAdapterViewHolder();
l_oViewHolder.eventName = (TextView) l_oRowView.findViewById(R.id.textview_event_name);
l_oViewHolder.eventCheckBox = (CheckBox) l_oRowView.findViewById(R.id.checkbox_for_event_name);
l_oViewHolder.eventName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// your code for textview click
}
}
l_oViewHolder.eventCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox)v;
//cb.setChecked(!cb.isChecked());
String l_sFilename = l_oViewHolder.eventName.getText().toString();
if (cb.isChecked())
{
if (!m_lstSelectedFilenames.contains(l_sFilename))
m_lstSelectedFilenames.add(l_sFilename);
}
else
{
if (m_lstSelectedFilenames.contains(l_sFilename))
m_lstSelectedFilenames.remove(l_sFilename);
}
}
});
l_oViewHolder.eventCheckBox.setFocusable(false);
add following attribute:
android:focusable="false"
android:clickable="false"
for example in my xml file:
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:button="?android:attr/listChoiceIndicatorSingle"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:buttonTint="#color/gray"
android:focusable="false"
android:clickable="false"
/>
and in my code:
public class MyTestFragment extends ListFragment {
.....
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
}
}
If I have a listview populated with objects lets say country names, and custom adapter how can I place inside a list item a facebook share button (assumming that I've setup fb account and app)
CustomAdapter:
public class MyAdapter extends BaseAdapter {
private ArrayList<String> list;
private LayoutInflater inflater;
public MyAdapter(ArrayList<String> list, Context context) {
this.list = list;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = inflater.inflate(R.layout.activity_main, null, false);
Button button = (Button) view.findViewById(R.id.share_button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}}
Xml:
<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="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="25dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/share_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_alignParentRight="true"
android:layout_marginRight="24dp"
android:text="Share" />
This is very short example, a lot of thing need to improve here.
You must declare button as final variable
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = inflater.inflate(R.layout.activity_main, null, false);
//Declare button as final variable
final Button button = (Button) view.findViewById(R.id.share_button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}}
Scenario:
User clicks a button and a row(adapter) is added. The user inputs a value and clicks on a button which is generated. The value would be computed and displayed in an edit text.
Problem: The value is not computed nor is it being displayed in the edit text. What am I doing wrong?
custom_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center">
<EditText
android:id="#+id/name"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:hint="Name"
android:maxLength="10"
/>
<EditText
android:id="#+id/price"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:hint="Price"
android:inputType="numberDecimal"
android:maxLength="5"
/>
<Button
android:id="#+id/calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
/>
</LinearLayout>
<EditText
android:id="#+id/result"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:editable="false"
android:cursorVisible="false"
android:text="$0.00"
/>
main.java <<EDITTED>>
public class AdvancedBillSplitter extends Activity{
ArrayList<String> noteList = new ArrayList<String>();
FancyAdapter aa = null;
Button calculate;
//EditText price;
EditText result;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView myListView = (ListView)findViewById(R.id.noteList);
aa = new FancyAdapter();
myListView.setAdapter(aa);
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
EditText price = (EditText)findViewById(R.id.price);
price = (EditText)findViewById(R.id.price);
double price1 = Double.parseDouble(price.getText().toString());
double total = price1 *1.1;
String resultPrice = Double.toString(total);
result.setText(resultPrice);
System.out.println(total);
}
});
aa.notifyDataSetChanged();
Button btnSimple = (Button)findViewById(R.id.btnSimple);
btnSimple.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
noteList.add(0, "");
aa.notifyDataSetChanged();
}
});
}
class FancyAdapter extends ArrayAdapter<String>
{
Button calculate;
EditText price;
EditText result;
FancyAdapter()
{
super(AdvancedBillSplitter.this, android.R.layout.simple_list_item_1, noteList);
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if(row == null)
{
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.custom_list_item, null);
}
return (row);
}
}
}
simple addition,
<Button
android:id="#+id/calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Calculate"
/>
its not catching click event because the list has 2 items which are focussable (The list item and the button) , so now thats an Ambiguous situation. so make the button not focussable. it still catches click events.
Maybe you want to use the recommended method setOnItemClickListener() on the ListView instead - I guess it is a bad style to set the listeners directly within the adapter.
Shouldn't
EditText price = (EditText)findViewById(R.id.price);
be
EditText price = (EditText)view1.findViewById(R.id.price);
(Note the view1)
Also, you have the findViewById() line twice.
You can use the Handler to update your view.
Like this:
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
aa.notifyDataSetChanged();
break;
default:
break;
}
}};
btnSimple.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
noteList.add(0, "");
mHandler.sendEmptyMessage(0);
}
});
Instead of using new AdapterView.OnItemClickListener(), You can use the new OnItemClickListener() which imports import android.widget.AdapterView.OnItemClickListener;
Dont have the click listener for the inflated layout and also for the parent layout(ie for listview). If you have the inflated layout's click listener then control will directly transfer there.
myListViewmyListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
price = (EditText)findViewById(R.id.price);
double price1 = Double.parseDouble(price.getText().toString());
double total = price1 *1.1;
String resultPrice = Double.toString(total);
result.setText(resultPrice);
}
});
I think this might give you some idea. And once the data has changed try to call the notifyDataSetChanged() method to refresh the view.
All the best.
class FancyAdapter extends BaseAdapter
{
Button calculate;
EditText price;
EditText result;
#Override
public int getCount() {
return noteList.length;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row == null)
{
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.custom_list_item, null);
}
return (row);
}
}