OnClickListener not triggered inside Fragment - java

I have custom class (ActionBar.class) where I implemented custom ActionBar component with OnClickListener (OnBackButtonClickListener).When I call this method in my fragment, it does not get triggered.
Here is my custom class:
public class ActionBar extends LinearLayout {
private boolean showBackButton;
private boolean showXButton;
private boolean showHeader;
private String header = "";
private OnClickListener onBackButtonClickListener;
private OnClickListener onXButtonClickListener;
#Bind(R.id.back) ImageView backButton;
#Bind(R.id.header) AutoResizeTextView headerText;
#Bind(R.id.x_btn) ImageView xButton;
public ActionBar(Context context) {
super(context);
initialize(context, null);
}
public ActionBar(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context, attrs);
}
public ActionBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize(context, attrs);
}
public ActionBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initialize(context, attrs);
}
private void initialize(Context context, AttributeSet attributeSet) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.action_bar_layout, this);
ButterKnife.bind(this, view);
if(attributeSet != null) {
TypedArray typedArray =
context.getTheme().obtainStyledAttributes(attributeSet, R.styleable.ActionBar, 0, 0);
try {
setHeader(typedArray.getString(R.styleable.ActionBar_header) == null ?
"" : typedArray.getString(R.styleable.ActionBar_header));
setShowBackButton(typedArray.getBoolean(R.styleable.ActionBar_show_back_button, false));
setShowXButton(typedArray.getBoolean(R.styleable.ActionBar_show_x_button, false));
setShowHeader(typedArray.getBoolean(R.styleable.ActionBar_show_header, false));
} finally {
typedArray.recycle();
}
}
}
public boolean isShowBackButton() {
return showBackButton;
}
public void setShowBackButton(boolean showBackButton) {
this.showBackButton = showBackButton;
invalidate();
requestLayout();
}
public boolean isShowXButton() {
return showXButton;
}
public void setShowXButton(boolean showXButton) {
this.showXButton = showXButton;
invalidate();
requestLayout();
}
public boolean isShowHeader() {
return showHeader;
}
public void setShowHeader(boolean showHeader) {
this.showHeader = showHeader;
invalidate();
requestLayout();
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
invalidate();
requestLayout();
}
public OnClickListener getOnBackButtonClickListener() {
return onBackButtonClickListener;
}
public void setOnBackButtonClickListener(OnClickListener onBackButtonClickListener) {
this.onBackButtonClickListener = onBackButtonClickListener;
}
public OnClickListener getOnXButtonClickListener() {
return onXButtonClickListener;
}
public void setOnXButtonClickListener(OnClickListener onXButtonClickListener) {
this.onXButtonClickListener = onXButtonClickListener;
}
#Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
backButton.setVisibility(showBackButton ? VISIBLE : INVISIBLE);
xButton.setVisibility(showXButton ? VISIBLE : INVISIBLE);
headerText.setVisibility(showHeader ? VISIBLE : INVISIBLE);
headerText.setText(header);
}
#OnClick(R.id.x_btn) void onXButtonClick(View v) {
if(getOnBackButtonClickListener() != null) {
getOnBackButtonClickListener().onClick(v);
}
}
#OnClick(R.id.back) void onBackButtonClick(View v) {
if(getOnXButtonClickListener() != null) {
getOnXButtonClickListener().onClick(v);
}
}
}
Here is my Fragment and method setOnBackButtonClickListener call:
public class ForgotPasswordFragment extends BasePagerFragment
implements ForgotPasswordView, TextView.OnEditorActionListener, ActionBar.OnClickListener{
#Bind(R.id.action_bar) ActionBar actionBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
actionBar.setOnBackButtonClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
navigateTo(LoginActivity.class);
}
});
}

You have
#OnClick(R.id.x_btn) void onXButtonClick(View v) {
if(getOnBackButtonClickListener() != null) {
getOnBackButtonClickListener().onClick(v);
}
}
#OnClick(R.id.back) void onBackButtonClick(View v) {
if(getOnXButtonClickListener() != null) {
getOnXButtonClickListener().onClick(v);
}
}
But it looks like it should be:
#OnClick(R.id.back) void onXButtonClick(View v) {
if(getOnBackButtonClickListener() != null) {
getOnBackButtonClickListener().onClick(v);
}
}
#OnClick(R.id.x_btn) void onBackButtonClick(View v) {
if(getOnXButtonClickListener() != null) {
getOnXButtonClickListener().onClick(v);
}
}

Use #Onclick(R.id.action_bar) void methodNAme()
{
//ToDo
}

Related

RecyclerView crashing in some circumstances : Java.lang.IndexOutOfBoundsException: Inconsistency detected

I am making a chat application . App is crashing when i upload an image to Firebase , after selecting image from gallery and start scrolling immediately crash the app, i am using FirebaseRecyclerAdapter .
Error getting package info: com.videocall.newhost
2022-11-16 11:59:23.173 23361-23361 AndroidRuntime pid-23361 E FATAL EXCEPTION: main
Process: com.videocall.newhost, PID: 23361
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionMessageView{c4fbbee position=4 id=-1, oldPos=-1, pLpos:-1 no parent} androidx.recyclerview.widget.RecyclerView{60b9448 VFED..... ........ 0,112-1080,1686 #7f0a01c3 app:id/recyMessage}, adapter:com.videocall.newhost.Adapter.AdapterMessages#9239bff, layout:com.videocall.newhost.Helper.WraperLinearLayout#e8d0fe7, context:com.videocall.newhost.Activity.MessageActivity#8e8b3d4
at androidx.recyclerview.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:6544)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6727)
at androidx.recyclerview.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:288)
at androidx.recyclerview.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:345)
at androidx.recyclerview.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:361)
at androidx.recyclerview.widget.GapWorker.prefetch(GapWorker.java:368)
at androidx.recyclerview.widget.GapWorker.run(GapWorker.java:399)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:233)
at android.os.Looper.loop(Looper.java:344)
at android.app.ActivityThread.main(ActivityThread.java:8212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:584)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)
FirebaseRecyclerAdapter
public class AdapterMessages extends FirebaseRecyclerAdapter<PojoMessages, AdapterMessages.MessageView> {
public AdapterMessages(#NonNull FirebaseRecyclerOptions<PojoMessages> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull MessageView viewHolder, int position, #NonNull PojoMessages pojoMessages) {
if (pojoMessages.isSender()) {
viewHolder.layReciver.setVisibility(View.GONE);
viewHolder.laySender.setVisibility(View.VISIBLE);
switch (pojoMessages.getType()) {
case "text": {
viewHolder.laySText.setVisibility(View.VISIBLE);
viewHolder.laySImage.setVisibility(View.GONE);
viewHolder.laySVoice.setVisibility(View.GONE);
viewHolder.txtSMessage.setText(pojoMessages.getMessage());
break;
}
case "image": {
viewHolder.laySText.setVisibility(View.GONE);
viewHolder.laySImage.setVisibility(View.VISIBLE);
viewHolder.laySVoice.setVisibility(View.GONE);
Picasso.get().load(pojoMessages.getUrl()).into(viewHolder.imgSData);
break;
}
case "voice": {
viewHolder.laySText.setVisibility(View.GONE);
viewHolder.laySImage.setVisibility(View.GONE);
viewHolder.laySVoice.setVisibility(View.VISIBLE);
break;
}
}
} else {
viewHolder.layReciver.setVisibility(View.VISIBLE);
viewHolder.laySender.setVisibility(View.GONE);
switch (pojoMessages.getType()) {
case "text": {
viewHolder.layRText.setVisibility(View.VISIBLE);
viewHolder.layRImage.setVisibility(View.GONE);
viewHolder.layRVoice.setVisibility(View.GONE);
viewHolder.txtRMessage.setText(pojoMessages.getMessage());
break;
}
case "image": {
viewHolder.layRText.setVisibility(View.GONE);
viewHolder.layRImage.setVisibility(View.VISIBLE);
viewHolder.layRVoice.setVisibility(View.GONE);
Picasso.get().load(pojoMessages.getUrl()).into(viewHolder.imgRData);
break;
}
case "voice": {
viewHolder.layRText.setVisibility(View.GONE);
viewHolder.layRImage.setVisibility(View.GONE);
viewHolder.layRVoice.setVisibility(View.VISIBLE);
// viewHolder.voiceRPlayerView.setAudio("https://www2.cs.uic.edu/~i101/SoundFiles/BabyElephantWalk60.wav");
break;
}
}
}
}
#NonNull
#Override
public MessageView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MessageView(LayoutInflater.from(parent.getContext()).inflate(R.layout.single_message_view, parent, false));
}
public class MessageView extends RecyclerView.ViewHolder {
CircleImageView imgRProfile;
RelativeLayout layRText, layRImage, layRVoice, laySText, laySImage, laySVoice, laySender, layReciver;
TextView txtRMessage, txtSMessage;
ImageView imgRData, imgSData;
public MessageView(#NonNull View itemView) {
super(itemView);
layReciver = itemView.findViewById(R.id.layReciver);
laySender = itemView.findViewById(R.id.laySender);
imgRProfile = itemView.findViewById(R.id.imgRProfile);
layRText = itemView.findViewById(R.id.layRText);
layRVoice = itemView.findViewById(R.id.layRVoice);
layRImage = itemView.findViewById(R.id.layRImage);
txtRMessage = itemView.findViewById(R.id.txtRMessage);
imgRData = itemView.findViewById(R.id.imgRData);
laySText = itemView.findViewById(R.id.laySText);
laySVoice = itemView.findViewById(R.id.laySVoice);
laySImage = itemView.findViewById(R.id.laySImage);
txtSMessage = itemView.findViewById(R.id.txtSMessage);
imgSData = itemView.findViewById(R.id.imgSData);
}
}
}
This adapter is used to populate the chat
I have tried all available solution like extending LayoutManager
public class WraperLinearLayout extends LinearLayoutManager {
public WraperLinearLayout(Context context) {
super(context);
}
public WraperLinearLayout(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public WraperLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
#Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (Exception e) {
Log.d("onLayoutChildren", "onLayoutChildren: "+e.getMessage());
}
}
#Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
}
This is activity where adapter is
public class MessageActivity extends AppCompatActivity {
private static final int SELECT_PICTURE = 2121;
RecyclerView recySuggestion, recyMessage;
AdapterSuggestion adapterSuggestion;
DatabaseReference userDb, myMsgRef, otherMsgRef;
Query query;
AdapterMessages adapterMessages;
EditText edMessage;
ImageView imgSendMsg, imgImageDoc;
WraperLinearLayout layoutManager;
StorageReference imgRef;
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
sendImage(result);
}
});
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
initialization();
adapterMessages.startListening();
adapterMessages.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int friendlyMessageCount = adapterMessages.getItemCount();
int lastVisiblePosition =
layoutManager.findLastCompletelyVisibleItemPosition();
// If the recycler view is initially being loaded or the
// user is at the bottom of the list, scroll to the bottom
// of the list to show the newly added message.
if (lastVisiblePosition == -1 || positionStart >= (friendlyMessageCount - 1)) {
recyMessage.scrollToPosition(positionStart);
}
}
});
onClick();
}
#Override
protected void onResume() {
super.onResume();
}
private void onClick() {
imgSendMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendTextMessage(edMessage.getText().toString());
edMessage.setText("");
}
});
imgImageDoc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGetContent.launch("image/*");
}
});
}
#Override
protected void onStop() {
super.onStop();
adapterMessages.stopListening();
}
private void sendImage(Uri file) {
imgRef.child(file.getLastPathSegment()).putFile(file).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(
new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String fileLink = task.getResult().toString();
//next work with URL
PojoMessages pojoMessages = new PojoMessages();
pojoMessages.setUrl(fileLink);
pojoMessages.setType("image");
pojoMessages.setSender(true);
myMsgRef.push().setValue(pojoMessages);
pojoMessages.setSender(false);
otherMsgRef.push().setValue(pojoMessages);
}
});
}
});
}
private void sendTextMessage(String text) {
PojoMessages pojoMessages = new PojoMessages();
pojoMessages.setMessage(text);
pojoMessages.setType("text");
pojoMessages.setSender(true);
myMsgRef.push().setValue(pojoMessages);
pojoMessages.setSender(false);
otherMsgRef.push().setValue(pojoMessages);
}
private void initialization() {
layoutManager = new WraperLinearLayout(this, LinearLayoutManager.VERTICAL, false);
userDb = FirebaseDatabase.getInstance().getReference().child(USER);
imgRef = FirebaseStorage.getInstance().getReference().child("image/");
myMsgRef = userDb.child("987654321").child(MESSAGE).child("8385958058");
otherMsgRef = userDb.child("8385958058").child(MESSAGE).child("987654321");
query = userDb.child("987654321").child(MESSAGE).child("8385958058");
FirebaseRecyclerOptions<PojoMessages> options = new FirebaseRecyclerOptions.Builder<PojoMessages>()
.setLifecycleOwner(this).setQuery(query, PojoMessages.class).build();
adapterMessages = new AdapterMessages(options);
imgImageDoc = findViewById(R.id.imgImageDoc);
edMessage = findViewById(R.id.edMessage);
imgSendMsg = findViewById(R.id.imgSendMsg);
recySuggestion = findViewById(R.id.recySuggestion);
recyMessage = findViewById(R.id.recyMessage);
recyMessage.setLayoutManager(layoutManager);
recyMessage.setAdapter(adapterMessages);
adapterSuggestion = new AdapterSuggestion();
recySuggestion.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recySuggestion.setAdapter(adapterSuggestion);
}
}

ViewPager - can't get the item position

I'm working on a collab project. My goal here is to display the ViewPager item position. I have tried several possible solutions such as trying getting from the addOnPageChangeListener and displaying the position, made a function to in IntroView class to get the position but couldn't get what I wanted. Here's my code structure. Any help would be gladly appreciated. Thanks in advance.
InroActivity.java
public class IntroActivity extends DialogFacebookActivity {
private IntroView mIntroView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ChatterApplication.getApplicationComponent().inject(this);
mIntroView = new IntroView(this);
setContentView(mIntroView);
mIntroView.setAdapter(new IntroPagerAdapter(getSupportFragmentManager()));
}
Here's my IntroView.java
public class IntroView extends CoordinatorLayout {
#Bind(R.id.view_pager)
ViewPager mViewPager;
public IntroView(Context context) {
super(context);
init();
}
public IntroView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public IntroView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void setAdapter(#NonNull PagerAdapter pagerAdapter) {
mViewPager.setAdapter(pagerAdapter);
}
public void goToNextPage() {
mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
}
public int displayItem(){
return mViewPager.getCurrentItem();
}
private void init() {
inflate(getContext(), R.layout.view_intro, this);
ButterKnife.bind(this);
}
}
Here's my IntroFragment.java
public class IntroFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
#Inject
EventBus mEventBus;
IntroView iv;
ViewPager vp;
public IntroFragment() {
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
ChatterApplication.getApplicationComponent().inject(this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
IntroPageView view;
if (sectionNumber == IntroPagerAdapter.TUTORIAL_PAGE_COUNT) {
view = new IntroPageViewLast(getContext());
} else {
view = new IntroPageView(getContext(), sectionNumber);
}
iv= new IntroView(getContext());
vp =(ViewPager) iv.findViewById(R.id.view_pager);
Toast.makeText(getContext(),"You are in: " + vp.getCurrentItem() ,Toast.LENGTH_LONG).show();
return view;
}
public static IntroFragment newInstance(int sectionNumber) {
IntroFragment fragment = new IntroFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
}
Here's my IntroPageView which is used by my fragment
public class IntroPageView extends RelativeLayout {
#Bind(R.id.intro_skip)
TextView mSkipButton;
#Bind(R.id.intro_tos_disclaimer_link)
TextView disclaimer;
#Bind(R.id.section_image)
ImageView mImageView;
private IntroPageViewListener mEventListener;
public IntroPageView(Context context, int sectionNumber) {
super(context);
init(sectionNumber);
}
public void setListener(IntroPageViewListener listener) {
this.mEventListener = listener;
}
protected void init(int sectionNumber) {
inflate(getContext(), R.layout.view_intro_fragment, this);
ButterKnife.bind(this);
mImageView.setImageResource(IntroPagerAdapter.TUTORIAL_IMAGE_IDS[sectionNumber - 1]);
}
Here's my *IntroPagerAdapter
public class IntroPagerAdapter extends FragmentPagerAdapter {
public static final int[] TUTORIAL_IMAGE_IDS = {
R.drawable.one,
R.drawable.two,
R.drawable.third,
R.drawable.four
};
public static final int TUTORIAL_PAGE_COUNT = TUTORIAL_IMAGE_IDS.length;
public IntroPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
int sectionNumber = position + 1;
return IntroFragment.newInstance(sectionNumber);
}
#Override
public int getCount() {
return TUTORIAL_PAGE_COUNT;
}
}
Turns out I forgot to use the butter ButterKnife.bind(this); while initializing my ViewPager. Hence, I was able to use addOnPageChangeListener to get the position. Here's the solution:
vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// Toast.makeText(getApplicationContext(), "You are in.....: " + (position + 1),Toast.LENGTH_LONG).show();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

Surfaceview to draw Thread error NULLPointerException

I'm a beginner in android. I'm creating a simple surface view to draw a thread (draw rectangle), but it keeps getting error like this :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int)' on a null object reference
and this is my code :
myActivity.java :
public class myActivity extends AppCompatActivity {
mySurfaceView mysurfaceview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ball);
//mysurfaceview = new mySurfaceView(this);
mysurfaceview = (mySurfaceView) findViewById(R.id.mySurfaceView);
mysurfaceview.RunThread();
}
mySurfaceview.java :
public class mySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
public DrawThread DrawThread;
private Rect myrectangle;
private Paint myPaint;
int moveX = 0;
private void init() {
myrectangle = new Rect(150, 150, 700, 500);
myPaint = new Paint();
myPaint.setColor(Color.BLUE);
}
public mySurfaceView(Context context) {
super(context);
//init();
}
public mySurfaceView(Context context, AttributeSet attrs, int defStyle){ super(context, attrs, defStyle); }
public mySurfaceView(Context context, AttributeSet attrs) { super(context, attrs); }
public void onDrawSomething(Canvas canvas) {
canvas.drawColor(Color.BLACK);
canvas.drawRect(myrectangle, myPaint);
}
#Override
public void surfaceCreated(SurfaceHolder holder) { }
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { }
#Override
public void surfaceDestroyed(SurfaceHolder holder) { }
public void update(){
}
public void RunThread() {
init();
DrawThread = new DrawThread(getHolder(), this);
DrawThread.setRunning(true);
DrawThread.start();
}
public class DrawThread extends Thread {
//var definition
public boolean run = false;
private SurfaceHolder surfaceHolder;
mySurfaceView mysurfaceView;
public DrawThread(SurfaceHolder surfaceHolder, mySurfaceView mysurfaceView) {
this.surfaceHolder = surfaceHolder;
this.mysurfaceView = mysurfaceView;
}
public void setRunning(boolean run) {
this.run = run;
}
#Override
public void run() {
while(run)
{
//implement fps counter
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
mysurfaceView.onDrawSomething(canvas);
//mysurfaceView.update();
}
} finally {
if(canvas != null)
{
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
}
And this is my XML code to show surface view :
<com.example.firstapp_aurelia.mySurfaceView
android:id="#+id/mySurfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Did I do anything wrong here? Thank you so much.
I didn't run you code but do not initial mySurfaceView twice
mysurfaceview = new mySurfaceView(this);
mysurfaceview = (mySurfaceView) findViewById(R.id.mySurfaceView);

Android custom button listener not getting called

I have a custom ImageButton and I want to change it's image on click. So far I havent been able to get the onClick method inside the button to perform it's action.
public class FlashButtonView extends ImageButton{
private Drawable mFlashOffSrc, mFlashOnSrc, mFlashAutoSrc;
private Drawable mCurrentFlashMode = mFlashAutoSrc;
public FlashButtonView(Context context) {
super(context);
}
public FlashButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context.getTheme().obtainStyledAttributes(attrs, R.styleable.FlashButtonView, 0, 0));
}
public FlashButtonView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context.getTheme().obtainStyledAttributes(attrs, R.styleable.FlashButtonView, 0, defStyleAttr));
}
private void init(TypedArray typedArray) {
try {
mFlashAutoSrc = typedArray.getDrawable(R.styleable.FlashButtonView_autoSrcImage);
mFlashOnSrc = typedArray.getDrawable(R.styleable.FlashButtonView_onSrcImage);
mFlashOffSrc = typedArray.getDrawable(R.styleable.FlashButtonView_offSrcImage);
} finally {
typedArray.recycle();
}
setImageDrawable(mFlashAutoSrc);
mCurrentFlashMode = mFlashAutoSrc;
setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
if(mCurrentFlashMode == mFlashAutoSrc) {
setImageDrawable(mFlashOnSrc);
mCurrentFlashMode = mFlashOnSrc;
}
else if(mCurrentFlashMode == mFlashOnSrc){
setImageDrawable(mFlashOffSrc);
mCurrentFlashMode = mFlashOffSrc;
}
else{
setImageDrawable(mFlashAutoSrc);
mCurrentFlashMode = mFlashAutoSrc;
}
}
});
}
}
And this is how my XML looks like:
<!--.___ Flash on/off switcher __.-->
<blablabla.FlashButtonView
custom:autoSrcImage="#drawable/button_autoflash"
custom:offSrcImage="#drawable/button_noflash"
custom:onSrcImage="#drawable/button_flash"
android:id="#+id/flash"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="#dimen/distance_20dp"
android:layout_marginStart="#dimen/distance_20dp"
android:layout_marginBottom="#dimen/distance_20dp"
android:background="#android:color/transparent"
android:clickable="true"/>
What am I missing or doing wrong?
Implement onTouchEvent() method. Something like this:
float touched_x, touched_y;
boolean touched = false;
#Override public boolean onTouchEvent(MotionEvent event) {
touchCounter++;
touched_x = event.getX();
touched_y = event.getY();
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
touched = true;
break;
case MotionEvent.ACTION_MOVE:
touched = true;
break;
case MotionEvent.ACTION_UP:
touched = false;
break;
case MotionEvent.ACTION_CANCEL:
touched = false;
break;
case MotionEvent.ACTION_OUTSIDE:
touched = false;
break; default:
}
return true;
}
A minimal example with:
public class CustomButton extends ImageButton {
public CustomButton(Context context) {
super(context);
init();
}
public CustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
this.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(getClass().getSimpleName(), "ButtonPressed");
}
});
}
}
and they layout:
<com.example.bossb.test.CustomButton
android:layout_width="match_parent"
android:layout_height="match_parent" />
works fine for me.

The endless listview charges every element

I know there are a lot of documentation about this topic, but I have a problem with the endless ListView. Each row must show a ProgressBar until the user scrolls, but it doesn't success. When the app starts, all the elements are loaded disappearing all the ProgressBar. Here is all the code.
public class MainActivity extends Activity implements EndlessListView.EndlessListener{
EndlessListView lv;
List<String> listOfElements;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = new RelativeLayout(this);
lv = new EndlessListView(this);
listOfElements = fillList();
EndlessAdapter adp = new EndlessAdapter(this, listOfElements,-1);
lv.setLoadingView();
lv.setAdapter(adp);
lv.fillAdapter(listOfElements);
lv.setListener(this);
layout.addView(lv);
setContentView(layout);
}
public List<String> fillList(){
List<String> listOfElements = new ArrayList<String>();
for (int i = 0; i < 200; i++) {
listOfElements.add("Element "+i );
}
return listOfElements;
}
}
public class EndlessListView extends ListView{
Context context;
private EndlessListener listener;
private EndlessAdapter adapter;
public EndlessListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EndlessListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EndlessListView(Context context) {
super(context);
}
public void setContext(Context context){
this.context = context;
}
public void setLoadingView() {
LinearLayout layout = new LinearLayout(super.getContext());
//this.addView(layout);
}
public void setAdapter(EndlessAdapter adapter) {
super.setAdapter(adapter);
this.adapter = adapter;
}
public EndlessListener setListener() {
return listener;
}
public void setListener(EndlessListener listener) {
this.listener = listener;
}
public static interface EndlessListener {
}
public void fillAdapter(List<String> data){
adapter.addAll(data);
adapter.notifyDataSetChanged();
}
}
And this is the critical code:
public class EndlessAdapter extends ArrayAdapter<String> {
private List<String> itemList;
private Context ctx;
private int layoutId;
public EndlessAdapter(Context ctx, List<String> itemList, int layoutId) {
super(ctx, layoutId, itemList);
this.itemList = itemList;
this.ctx = ctx;
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public String getItem(int position) {
return itemList.get(position);
}
#Override
public long getItemId(int position) {
return itemList.get(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv = new TextView(ctx);
ProgressBar pg = new ProgressBar(ctx);
if (convertView == null) {
tv = new TextView(ctx);
pg = new ProgressBar(ctx);
convertView = pg;
} else {
pg = (ProgressBar) convertView;
}
//tv.setText(itemList.get(position));
FakeImageLoader fake = new FakeImageLoader(tv, pg, position);
fake.execute();
System.out.println("Me estoy pintando y soy el elemento "
+ itemList.get(position));
return convertView;
}
private class FakeImageLoader extends AsyncTask<String, Void, TextView> {
private TextView tv;
private ProgressBar pg;
private int position;
public FakeImageLoader(TextView tv,
ProgressBar pg, int position) {
this.tv = tv;
this.pg = pg;
this.position = position;
}
protected void onPreExecute() {
}
protected TextView doInBackground(String... params) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return createItem(position);
}
protected void onPostExecute(TextView text) {
tv = text;
addNewData(tv, pg,position);
}
public TextView createItem(int position) {
TextView text = new TextView(ctx);
text.setText(itemList.get(position));
System.out.println(itemList.get(position));
text.setTextSize(20);
return text;
}
}
public void addNewData(TextView text, ProgressBar pg, int position) {
System.out.println("Entra");
pg.setVisibility(View.INVISIBLE);
text.setText(itemList.get(position));
}
}
Regards.

Categories

Resources