Android: setOnItemClickListener doesn't work - java

I'm attempting to implement a `setOnItemClickListener however it never seems to fire for some reason. The most common fix for this seems to be adding:
android:focusable="false"
android:focusableInTouchMode="false"
`
...however I still cannot seem to reach the setOnItemClickListener or fire the toast within it.
Any suggestions are appreciated.
Java Source:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preinstall_activity);
mContext = PreinstallActivity.this;
//fetchLinks(final UserData userData);
fetchLinks();
gridView = (GridView) findViewById(R.id.gridView2);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(PreinstallActivity.this, mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
}
XML Source:
<?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:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".PreinstallActivity">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:background="#color/primaryColor"
android:layout_width="match_parent"
android:paddingRight="10dp"
android:layout_height="wrap_content"
app:theme="#style/FreeMo.ToolBarStyle"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
<ImageView
android:id="#+id/action_bar"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center|start"
android:background="#drawable/ic_toggle"
/>
<TextView
android:id="#+id/headline_text"
android:paddingLeft="20dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/rec_apps_title"
android:textColor="#color/edit_text"
android:textSize="#dimen/headline_text_size" />
<ImageView
android:id="#+id/user_icon"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center|end"
android:background="#drawable/ic_menu"></ImageView>
</android.support.v7.widget.Toolbar>
<TextView
android:id="#+id/rec_apps_txt"
android:padding="12dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/rec_apps_txt"
android:textColor="#color/text_view"
android:textSize="#dimen/default_text_size" />
<GridView
android:layout_height="wrap_content"
android:id="#+id/gridView2"
android:layout_width="match_parent"
android:numColumns="auto_fit"
android:horizontalSpacing="10dp"
android:verticalSpacing="0dp">
</GridView>
</LinearLayout>
XML Source 2:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="5dp">
<ImageView
android:layout_height="64dp"
android:id="#+id/imageView1"
android:layout_width="64dp"
android:src="#drawable/ic_lock_handle"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
<TextView
android:text="TextView"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_marginTop="0dp"
android:layout_centerHorizontal="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:textSize="10sp"
android:ellipsize="marquee"></TextView>
</RelativeLayout>
Java Source 2:
public class PreinstallAdapter extends BaseAdapter
{
private ArrayList<String> listCountry;
private ArrayList<String> listFlag;
private Activity activity;
public PreinstallAdapter(Activity activity, ArrayList<String> listCountry, ArrayList<String> listFlag) {
super();
this.listCountry = listCountry;
this.listFlag = listFlag;
this.activity = activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listCountry.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listCountry.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public ImageView imgViewFlag;
public TextView txtViewTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.preinstall_grid, null);
view.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
view.imgViewFlag = (ImageView) convertView.findViewById(R.id.imageView1);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtViewTitle.setText(listCountry.get(position));
Picasso.with(activity).load(listFlag.get(position)).into(view.imgViewFlag);
// view.imgViewFlag.setImageResource(listFlag.get(position));
return convertView;
}
}

1.make sure that your Gridview have width and height.
2.add
android:focusable="false"
android:focusableInTouchMode="false"
to the LinearLayout . like this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:focusable="false"
android:focusableInTouchMode="false"
```````````````````````````````````>

Related

Getting the progress of multiple seekbars in recycler view

So I am displaying a recylerview with an Image and the name of a person. Below that is a seekbar, which the user can move to rate that person.
Now I want to store the ratings (=progress) of each seekbar in a list. However right now it only stores the rating of the last seekbar in the list.
So it stores only the progress of the last seekbar right now. I would like that when the user clicks the button that every current rating value of every seekbar is stored in a list.
Thank you very much.
That is is my layout_listitem:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="3dp"
android:id="#+id/parent_layoutREC"
android:orientation="horizontal"
android:layout_marginTop="13dp"
android:gravity="center">
<de.hdodenhof.circleimageview.CircleImageView
android:paddingTop="2dp"
android:paddingLeft="2dp"
android:layout_width="73dp"
android:layout_height="73dp"
android:id="#+id/kunde_imageREC"
android:src="#mipmap/ic_launcher"/>
<TextView
android:layout_marginLeft="40dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Canada"
android:id="#+id/kunde_nameREC"
android:textColor="#000"
android:textSize="19sp"
android:textStyle="bold"/>
</LinearLayout>
<SeekBar
android:layout_marginRight="35dp"
android:layout_marginLeft="35dp"
android:layout_marginTop="8dp"
android:id="#+id/seek_Bar"
android:max="10"
android:progress="5"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0 1 2 3 4 5"
android:textSize="20sp"/>
That is my RecyclerViewAdapter class:
public class RecyclerViewAdap extends
RecyclerView.Adapter<RecyclerViewAdap.ViewHolder> {
private static final String TAG = "RecyclerViewAdap";
private ArrayList<String> mImageUrl = new ArrayList<>();
private ArrayList<String> mKundeNamen = new ArrayList<>();
public ArrayList<Integer> mBewertungen = new ArrayList<>();
private Context mContext;
public String bewertung;
private TextView progressSeekbar;
public RecyclerViewAdap(ArrayList<String> imageUrl, ArrayList<String> kundeNamen, Context context) {
mImageUrl = imageUrl;
mKundeNamen = kundeNamen;
mContext = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView imageView;
TextView kundeName;
LinearLayout parentLayout;
SeekBar seekBar1;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.kunde_imageREC);
kundeName = itemView.findViewById(R.id.kunde_nameREC);
parentLayout = itemView.findViewById(R.id.parent_layoutREC);
seekBar1 = itemView.findViewById(R.id.seek_Bar);
progressSeekbar = itemView.findViewById(R.id.progress_seekbar);
seekBar1.setOnSeekBarChangeListener(seekBarChangeListener);
//int progress = seekBar1.getProgress();
//String.valueOf(Math.abs((long)progress)).charAt(0);
//progressSeekbar.setText("Bewertung: " +
// String.valueOf(Math.abs((long)progress)).charAt(0) + "." + String.valueOf(Math.abs((long)progress)).charAt(1));
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
ViewHolder holder = new ViewHolder(view);
Log.d(TAG, "onCreateViewHolder: ");
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(mContext)
.load(mImageUrl.get(position))
.into(holder.imageView);
holder.kundeName.setText(mKundeNamen.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, mKundeNamen.get(position),
Toast.LENGTH_SHORT).show();
}
});
holder.seekBar1.setTag(position);
}
#Override
public int getItemCount() {
return mImageUrl.size();
}
SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// updated continuously as the user slides the thumb
progressSeekbar.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// called when the user first touches the SeekBar
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// called after the user finishes moving the SeekBar
if (seekBar.getTag().toString().equals("1")) {
mBewertungen.add(seekBar.getProgress());
if (mBewertungen.size() == 2) {
mBewertungen.remove(0);
Toast.makeText(mContext, "onProgressChanged: " + mBewertungen.toString(), Toast.LENGTH_SHORT).show();
}
}
if (seekBar.getTag().toString().equals("2")) {
mBewertungen.add(seekBar.getProgress());
if (mBewertungen.size() == 3) {
mBewertungen.remove(1);
Toast.makeText(mContext, "onProgressChanged: " + mBewertungen.toString(), Toast.LENGTH_SHORT).show();
}
}
}
};
}
That is the activity where the Recyclerview is being displayed:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BewertungEsserActvity"
android:orientation="vertical"
app:layoutManager="LinearLayoutManager"
android:background="#drawable/gradient_background">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="14dp"
android:text="Bewerte deine Gäste"
android:textColor="#color/colorDarkGrey"
android:textSize="30sp"
android:textStyle="bold" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorBlack"
android:layout_marginBottom="10dp"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view">
</androidx.recyclerview.widget.RecyclerView>
<ProgressBar
android:visibility="invisible"
android:id="#+id/progressbar_4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="13dp" />
<Button
android:layout_marginRight="66dp"
android:layout_marginLeft="66dp"
android:id="#+id/bewerten_Btn"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_marginTop="10dp"
android:background="#drawable/btn_background_profil"
android:padding="10dp"
android:text="Bewerten"
android:textAllCaps="false"
android:textColor="#color/colorWhite"
android:textSize="16sp"
android:textStyle="normal" />
<View
android:layout_marginBottom="10dp"
android:layout_marginTop="34dp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#color/colorBlack" />
</LinearLayout>
</ScrollView>
You can do it in multiple ways:
1- You can store seekbars value as a property in your model and update that property on OnSeekBarChangeListener and when the user hits the button get the data source from the adapter and then run a loop on it and call getter of that attribute.
2- You can store seekbars value as a List<> in your adapter and whenever the user hits the button get the list from the adapter.

custom listview on fragment - can't use getActivity()

I am trying to add delete button next to my item details basing on this answer.
I tried it on a new project, it works perefect:
and when I click delete, I delete the item.
sadly, I tried to use it in my own project when my listView is in calendar_tab.xml. calendar_tab uses CompactCalendarTab.java - fragment class.
so Android Studio errored:
E:\Downloads\MyCustomAdapter.java
Error:(49, 63) error: cannot find symbol method getSystemService(String)
I tried to change
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
to
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
but with no luck.
custom_listview.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Delete" />
calendar_tab.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:id="#+id/calendar_tab"
android:layout_height="match_parent"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/toolbar_calendar"
android:background="#color/teal_300"
android:layout_alignParentTop="true"
android:padding="10sp"
android:layout_alignParentStart="true">
<ImageButton
android:id="#+id/back_button"
android:src="#mipmap/ic_arrow_back_black_24dp"
android:background="#null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="goBackmain"
/>
<ImageButton
android:id="#+id/next_button"
android:src="#mipmap/ic_keyboard_arrow_left_black_24dp"
android:background="#null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/showdate"
android:layout_toStartOf="#+id/showdate" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="25sp"
android:textStyle="bold"
android:textColor="#color/black"
android:id="#+id/showdate"
android:layout_alignBaseline="#+id/prev_button"
android:layout_alignBottom="#+id/prev_button"
android:layout_centerHorizontal="true" />
<ImageButton
android:id="#+id/prev_button"
android:src="#mipmap/ic_keyboard_arrow_right_black_24dp"
android:background="#null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/showdate"
android:layout_toEndOf="#+id/showdate" />
</RelativeLayout>
<com.github.sundeepk.compactcalendarview.CompactCalendarView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/compactcalendar_view"
android:layout_width="fill_parent"
android:layout_height="250dp"
app:compactCalendarTargetHeight="250dp"
app:compactCalendarTextSize="12sp"
app:compactCalendarBackgroundColor="#null"
app:compactCalendarTextColor="#color/blue_grey_700"
app:compactCalendarCurrentSelectedDayBackgroundColor="#color/teal_300"
app:compactCalendarCurrentDayBackgroundColor="#color/teal_600"
app:compactCalendarCurrentDayIndicatorStyle="fill_large_indicator"
app:compactCalendarEventIndicatorStyle="small_indicator"
app:compactCalendarOtherMonthDaysTextColor="#534c4c"
app:compactCalendarShouldSelectFirstDayOfMonthOnScroll="true"
android:layout_below="#+id/toolbar_calendar"
/>
<ListView
android:id="#+id/bookings_listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/compactcalendar_view"
>
</ListView>
my fragment:
public class CompactCalendarTab extends Fragment {
final ListView bookingsListView = (ListView) v.findViewById(R.id.bookings_listview);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, mutableBookings);
final ArrayList<String> list = new ArrayList<>();
final MyCustomAdapter adapter = new MyCustomAdapter(list, this);
bookingsListView.setAdapter(adapter);
compactCalendarView = (CompactCalendarView)
v.findViewById(R.id.compactcalendar_view);
}
my custom adapter:
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private CompactCalendarTab context;
public MyCustomAdapter(ArrayList<String> list, CompactCalendarTab context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.custom_listview, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
return view;
}
}
Change this line
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
To this
LayoutInflater inflater = LayoutInflater.from(parent.getContext());

Implement custom Android grid view

I have made a custom gridView and a item witch I want to implement in the gridView, but how can I set these custom gridView onCreate inside my HomeActivity class file?
HomeActivity.java
public class HomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// how can I say here that I want to set the gridView from list_holder.xml
}
}
list_holder.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/view_item_block_holder"
android:layout_alignParentEnd="false"
android:numColumns="auto_fit"
tools:listitem="#layout/item_block" />
</RelativeLayout>
item_block.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/item_block"
android:padding="5dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#color/secondaryBackgroundColor">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/secondaryBackgroundColor"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:paddingRight="10dp">
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:id="#+id/imageView2"
android:background="#drawable/no_image_available" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/secondaryBackgroundColor"
android:padding="10dp"
android:layout_margin="5dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="video title"
android:id="#+id/item_block_title"
android:textColor="#color/textTitleColor"
android:textStyle="bold"
android:textSize="15dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/item_block_description"
android:textColor="#color/textContentColor"
android:textSize="10dp"
android:layout_weight="1" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="12-09-16"
android:id="#+id/item_date"
android:textColor="#color/textContentColor"
android:textSize="10dp"
android:layout_weight="2" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
HomeActivity.java
public class HomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//Here Adapter like
AdapterDemoGrid adapterDemoGrid = new AdapterDemoGrid(this);
gridView.setAdapter(adapterDemoGrid);
}
}
Here, Adapter for Custom GridView Make this class :
public class AdapterDemoGrid extends BaseAdapter {
private final Context context;
private LayoutInflater mLayoutInflater;
public AdapterDemoGrid(Context context) {
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
//lastPosition = -1;
}
#Override
public int getCount() {
return 20;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
ViewHolder holder = null;
if (view == null) {
//The view is not a recycled one: we have to inflate
view = mLayoutInflater.inflate(R.layout.item_block.xml, viewGroup, false);
holder = new ViewHolder();
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
return view;
}
class ViewHolder {
/// Item Block views goes here...
}
}
Hopefully it will help you !!

onClickListener on a button that is added through a layout inflator

Here is my code so far based on various answers to related questions on SO.
In my Activity
GridView gv = (GridView) findViewById(R.id.gridView1);
MyCustomAdapter mAdapter = new MyCustomAdapter();
mAdapter.addItem("Action1");
mAdapter.addItem("Action2");
mAdapter.addItem("Action3");
gv.setAdapter(mAdapter);
My Adapter
private class MyCustomAdapter extends BaseAdapter {
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
NumericViewHolder holder = new NumericViewHolder();
if (convertView == null) {
convertView = mInflater.inflate(R.layout.horizontalnumberpicker, null);
holder.textView = (TextView)convertView.findViewById(R.id.txtNPTitle);
holder.minus = (Button)convertView.findViewById(R.id.btnMinus);
holder.plus = (Button)convertView.findViewById(R.id.btnPlus);
holder.value = (TextView)convertView.findViewById(R.id.txtNPValue);
holder.minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
int value = Integer.parseInt(tv.getText().toString());
Toast.makeText(getApplicationContext(), Integer.toString(value), Toast.LENGTH_SHORT).show();
if (value > 0) {
value = value - 1;
tv.setText(Integer.toString(value));
}
}
});
holder.plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
int value = Integer.parseInt(tv.getText().toString()); <--Error is here
Toast.makeText(getApplicationContext(), Integer.toString(value), Toast.LENGTH_SHORT).show();
value = value + 1;
tv.setText(Integer.toString(value));
}
});
convertView.setTag(holder);
} else {
holder = (NumericViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
XML - Main_Activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rlAddProduct"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/btnSaveProduct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:text="#string/Save" />
<TextView
android:id="#+id/lblSelectCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnSaveProduct"
android:layout_alignBottom="#+id/btnSaveProduct"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:text="#string/selectCategory" />
<Spinner
android:id="#+id/spCategory"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_alignBottom="#+id/lblSelectCategory"
android:layout_marginLeft="33dp"
android:layout_marginStart="33dp"
android:layout_toEndOf="#+id/lblSelectCategory"
android:layout_toRightOf="#+id/lblSelectCategory" />
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/lblSelectCategory"
android:layout_below="#+id/btnSaveProduct"
android:layout_marginTop="14dp"
android:numColumns="auto_fit" >
</GridView>
</RelativeLayout>
XML - Horizontalnumberpicker
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtNPTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="EnterTextHere"
android:layout_marginTop="5dp" />
<Button
android:id="#+id/btnPlus"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignBaseline="#+id/txtNPValue"
android:layout_alignBottom="#+id/txtNPValue"
android:layout_toRightOf="#+id/txtNPValue"
android:text="+" />
<TextView
android:id="#+id/txtNPValue"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignTop="#+id/btnMinus"
android:layout_toRightOf="#+id/btnMinus"
android:gravity="center"
android:text="0"
android:textAppearance="#style/AppBaseTheme"
android:textSize="20dp" />
<Button
android:id="#+id/btnMinus"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtNPTitle"
android:layout_marginTop="2dp"
android:text="-" />
</RelativeLayout>
The requirement is that when I press the plus button, I need to increment the value in the corresponding txtNPValue. Similarly with the minus button, I need to decrement the value in the txtNPValue.
The error is
01-31 22:40:10.854: E/AndroidRuntime(32198): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
Also I do not know if this is the right way to program such a requirement and would like some pointers.
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
this will return null pointer exception, as the view that u r getting is of the button or the clicked item..
Use this :-
RelativeLayout rlLayout = (RelativeLayout) v.getParent();
TextView tv = (TextView) rlLayout.findViewById(R.id.txtNPValue);
please remove:
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
from onClick to resolve nullpointerException

Android ListView OnClickListener

I need to add a code responsible for action when one row from my list is clicked. I don't know if it should be OnItemClickListener or OnClickListener and how&where to write it. My app is with view holder. Here is my code:
public class JobListAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
public static class WorkViewHolder {
public TextView mJob;
public ImageView mImageAndroKorpo;
}
public JobListAdapter(Context mContext, List<String> mDane) {
super(mContext, R.layout.list_element_job, mDane);
this.mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
WorkViewHolder mHolder;
if(convertView == null) {
convertView = mInflater.inflate(R.layout.list_element_job, parent, false);
mHolder = new WorkViewHolder();
TextView mJobsName = (TextView) convertView.findViewById(R.id.nazwa_oferty);
ImageView mImageAndroKorpo = (ImageView)convertView.findViewById(R.id.list_image);
mHolder.mJob = mJobsName;
mHolder.mImageAndroKorpo = mImageAndroKorpo;
convertView.setTag(mHolder);
} else {
mHolder = (WorkViewHolder)convertView.getTag();
}
final String mWorkPosition = getItem(position);
mHolder.mJob.setText(mWorkPosition);
mHolder.mJob.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here?
}
});
return convertView;
}
}
I added code where I think it should be placed. Is it ok? OnItem or OnClick? And how to use item position?
My list_element_job.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:padding="10dp"
<CheckBox
android:id="#+id/list_checkbox"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/list_image"
android:src="#drawable/android_white_piece"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_width="1dp"
android:layout_height="1dp"/>
<TextView
android:text=""
android:background="#drawable/android_korpo_transparent3"
android:textStyle="bold"
android:textColor="#android:color/black"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:gravity="left"
android:layout_toLeftOf="#id/list_image"
android:layout_width="0dp"
android:textSize="7pt"
android:layout_height="wrap_content"
android:id="#+id/nazwa_oferty"/>
<TextView
android:text="Details..."
android:background="#android:color/white"
android:clickable="true"
android:focusable="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:layout_below="#id/nazwa_oferty"
android:textSize="6pt"
android:textColor="#android:color/darker_gray"/>
</RelativeLayout>
Please help me somehow :)
Just remove the focus for the checkbox in xml like below:
<CheckBox
android:id="#+id/list_checkbox"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
because of check box focus list item click listeners wont work.
Just remove onClick from your adapter class. And add OnItemClickListener to your ListView
example:
JobListAdapter jobListAdapter = new JobListAdapter (...);
listView.setAdapter(jobListAdapter);
listView..setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
});

Categories

Resources