onCreate got invoked onClick of the imageview in android - android

I have ScreenRecorder activity invoking RecorderService. RecorderService setting floating view with imageview. when i onclick on image view ScreenRecorder oncreate got called not able to invoke onclick action. But OnTouchListener working fine
<ImageView
android:id="#+id/sr_float_home"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginTop="8dp"
android:src="#drawable/recorder"
android:onClick="startRecord"
tools:ignore="ContentDescription"/>
ScreenRecorder activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate " );
mProjectionManager = (MediaProjectionManager)
getSystemService(Context.MEDIA_PROJECTION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, CODE_DRAW_OVER_OTHER_APP_PERMISSION);
} else {
recordeScreen();
}
Log.d(TAG,"onCreate end");
}
private void recordeScreen() {
Log.d(TAG, "recordeScreen open " );
if (mMediaProjection == null) {
startService(new Intent(ScreenRecorder.this, RecorderService.class));
finish();
return;
}
Log.d(TAG, "recordeScreen open end " );
}
public void startRecord(){
Log.d(TAG, "startRecord start " );
startActivityForResult(mProjectionManager.createScreenCaptureIntent(),
PERMISSION_CODE_SR);
Log.d(TAG, "startRecord end " );
finish();
return;}
RecorderService
#Override
public void onCreate() {
super.onCreate();
mChatHeadView = LayoutInflater.from(this).inflate(R.layout.activity_screen_recorder, null);
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mChatHeadView, params);
final ImageView srFloatHome = (ImageView)
mChatHeadView.findViewById(R.id.sr_float_home);
srFloatHome.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
}
}
}
i have also tried placing startRecord method like ontouch , but still not working. can someone please tell me why onclick call not received insteated it calling activity oncreate.

Seems like you're missing the parameter on your startRecord function. From Android documentation:
public static final int onClick
Name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View. For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity)

Maybe your code less a property in xml.
android:clickable="true"
if you want ImageView have the clicked method ,should add this,
this is demo code .xml:
<ImageView
android:id="#+id/image"
android:layout_width="100dp"
android:layout_height="200dp"
android:background="#android:color/background_dark"
android:onClick="StartDoSomething"
android:clickable="true"/>
and in .java is
public void ButtonClick(View v){
System.out.println("Do something here!");
}
hope to help you.

I have used layout root element and used below code i am able to get onclick in recorderervices
mChatHeadView.findViewById(R.id.sr_float_home);
form
final View srFloatHome = mChatHeadView.findViewById(R.id.sr_head_root);
srFloatHome.setOnClickListener(this);
my onclick method in RecorderService
public void startRecord(View v){}

Related

onClickListener not found after rotation in android

This is a stripped down version of what I want to do. I have some stuff occurring inside the clickListener and want it to continue after orientation change. I save the variable and in the "if(saveInstanceState != null) section I retrieve the variable "count" and try to start the tasks inside the onClick method. The variable is saved properly (although not printed because the setText method in inside onClick. Also, the Log returns "false", meaning that the performClick method executed but did not find the clickListener.
I think this is a scope of variable issue, but am otherwise stumped. Thanks for any help.
public class MainActivity extends Activity {
Button countButton;
int count = 0;
TextView countWidget;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countButton = (Button)findViewById(R.id.button);
countWidget = (TextView)findViewById(R.id.textView);
if (savedInstanceState != null){
count = savedInstanceState.getInt("count");
boolean found = countButton.performClick();
Log.d("Message ", "found listener = " + found);
}
countButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count ++;
countWidget.setText("count = " + count);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("count", count);
}
}
Because you are calling performClick() before the call to setOnClickListener, thus when onCreate is called with your Bundle, it cannot find the callback.
The previous call is fine because when the user taps on the button, it's already way past onCreate where the callback is defined.
One solution is to move the Bundle check after setOnClickListener
countButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count ++;
countWidget.setText("count = " + count);
}
});
if (savedInstanceState != null){
count = savedInstanceState.getInt("count");
boolean found = countButton.performClick();
Log.d("Message ", "found listener = " + found);
}
performClick works (without crashing, if that's what you were expecting when the log returns false) because Android will check if there's any click listener defined, if not then just return false.
https://github.com/android/platform_frameworks_base/blob/master/core/java/android/view/View.java
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
You can also set the onClick function from the layout file of your activity like this:
<Button
android:id="#+id/countButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Count"
android:onClick="onCountClick"/>
Now, after adding this to your layout file, define the function onCountClick in your activity's java file like this:
public void onCountClick(View v)
{
//Do your tasks here
}
If you do this, you won't be needing the onClickListener any more.
Hope it helps.

ImageView is not loading correctly

In my Activity I have one ImageView
XML Code:
<!-- FOTO LATERAL! -->
<ImageView
android:id="#+id/simbolo_raca"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<Button
android:id="#+id/button_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok. Seguinte Pergunta"
android:layout_gravity="right"
android:gravity="right"
android:paddingRight="30dip">
</LinearLayout>
This is the Activity:
public class QuestionarioActivityRaca extends Activity{
ImageView simbolo;
int position;
Button B_Save;
List<Drawable> List_imagens = new ArrayList<Drawable>();
#Override
public void onCreate(Bundle savedInstanceState) {
simbolo = (ImageView) findViewById(R.id.simbolo_raca);
B_Save = (Button) findViewById(R.id.button_save);
position = 0;
List_imagens.add(getResources().getDrawable(R.drawable.p1));
List_imagens.add(getResources().getDrawable(R.drawable.p2));
List_imagens.add(getResources().getDrawable(R.drawable.p3));
List_imagens.add(getResources().getDrawable(R.drawable.p4));
loadNewImage(position);
B_Save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
loadNewImage(position);
position++;
}
});
}
// I Use this method to load the Image
public loadNewImage(int Page)
{
new Thread(new Runnable(){
#Override
public void run(){
simbolo.post(new Runnable(){
#Override
public void run()
{
simbolo.setImageDrawable(List_imagens.get(Page));
}
});
}
}).start();
}
The first time I call this method, (position = 0) the image doesnt loads. After that, the image is loading correctly.
How I have to do to load the image the first time?
(I can not load the image in the XML using android:src="#drawable/x") because the image could be different anytime.
EDITED!
There are a number of issues with the code sample you posted.
like writing int with a capital I.
Int position;
Not sending in a parameter with your method in the onClick:
public void onClick(View v) {
loadNewImage();
}
And several more in both your XML and code.
Is there a spesific reason you want to run a new thread every time for this task?
If you really need a thread, you have to declare your int as final in the method.
However, you should get your desired result with the code-sample below.
You have to modify your onClick to send the appropriate int for whatever drawable you want to use.
Good luck.
public class testactivity extends ActionBarActivity {
ImageView simbolo;
int position;
Button B_Save;
List<Drawable> List_imagens = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testactivity);
simbolo = (ImageView) findViewById(R.id.simbolo_raca);
B_Save = (Button) findViewById(R.id.button_save);
position = 0;
List_imagens.add(getResources().getDrawable(R.drawable.ic_drawer));
List_imagens.add(getResources().getDrawable(R.drawable.ic_check));
List_imagens.add(getResources().getDrawable(R.drawable.ic_action_add_package));
List_imagens.add(getResources().getDrawable(R.drawable.ic_action_exception));
loadNewImage(position);
final Random rand = new Random();
B_Save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
loadNewImage(rand.nextInt(4));
}
});
}
public void loadNewImage(final int page)
{
simbolo.setImageDrawable(List_imagens.get(page));
}
}
first of all before the button gets clicked you call this function to load the initial image with loadNewImage(position); when the button is clicked you call this function loadNewImage(); i am guessing it works when the button is clicked because this loadNewImage(); method is ok and loadNewImage(int page); is not ok, because they are two different function.
Solving your problem if you want an integer object use Integer position or else go with int position and please let go of the thread. now your code will work

Android: onClick not sent by child of layout

In an Android app, I want to handle clicks both on a background element and on foreground elements. In my test case, clicks on the foreground elements do not get sent.
I've taken a barebones Hello World project called Test, and altered it as follows.
In activity_test.xml, I have set ids for the layout and the TextView, and I have given them both onClick properties:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
...
android:id="#+id/layout"
android:onClick="doStuff">
<TextView
...
android:id="#+id/hello_world"
android:textSize="52dp"
android:onClick="doStuff" />
</RelativeLayout>
In the main TestActivity class, I have the following class:
public class TestActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
TextView view = (TextView) findViewById(R.id.hello_world);
doStuff(view);
Log.d("onCreate", "testing " + view.getId());
}
public void doStuff(TextView textView) {
Log.d("test", "text " + textView.getId() + " " + R.id.hello_world);
}
public void doStuff(View view) {
Log.d("test", "view " + view.getId() + " " + R.id.layout);
}
}
In the log window, after launching the app, I see the following:
D/test﹕ text 2131165250 2131165250
D/onCreate﹕ testing 2131165250
This shows that the TestView version of the doStuff method is definitely triggered when a TestView parameter is sent.
However, if I now tap on the Hello World TextView, this is the line that is added to the log:
D/test﹕ view 2131165249 2131165249
In other words, tapping the Hello World text has the same effect as tapping on the background itself. What do I need to do to get the TextView element to respond to its onClick setting?
What you're missing is:
android:clickable="true"
The TextView is not clickable by default.
hi can you use setOnTouchListener? then you can refer below given code.. it may work i think..
as per my knowledg, the problem is , whenever you touch textview, it will call onTouchListener for both textview and background.. sorry for my bad english
private int textViesTouchStatus = 0;//public variable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView view = (TextView) findViewById(R.id.textView1);
view.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
textViesTouchStatus = 1;
Log.d("touch_textview", "code that should be run on textview touch goes here");
return false;
}
});
RelativeLayout layout = (RelativeLayout) findViewById(R.id.lay);
layout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (textViesTouchStatus == 1)
textViesTouchStatus = 0;
else
Log.d("touch_background", "code that should be run on layout touch goes here");
return false;
}
});

Allow command on "if statement" being satisfied

I currently have a command that will allow the user to proceed to the next page if a button is clicked, this button has a feature android:onClick="advancenext" which I have defined in the .java file to be the following
public void advancenext (View view) {
Intent intent = new Intent(Prompt1.this, Prompt2.class);
Prompt1.this.startActivity(intent);
}
However, I only want the user to call advancenext if a variable i is greater than 5. This is what I tried
if (i>5) {
public void advancenext (View view) {
Intent intent = new Intent(Prompt1.this, Prompt2.class);
Prompt1.this.startActivity(intent);
}
}
However, when I run the app, I can still advance even though i is not greater than 5. Does anyone know how to fix this, or better restrict advancenext in a different way?
EDIT Thanks for the great answers, but I encountered a different error when I changed my statement. When I try:
public void advancenext (View view) {
if (i>5) {
Intent intent = new Intent(Prompt1.this, Prompt2.class);
Prompt1.this.startActivity(intent);
}
}
I get the errors Syntax error on token "(", ; expected and Syntax error on token ")", ; expected around the ( and ) of (View view).
EDIT dos Here's my full code
public class Prompt1 extends Activity {
int i; //Variable i stores the touch number
float[] X, Y; //Array that will store the touchpoints
int ultscore1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prompt1);
i=1;
touchLayout.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event){
i++; //increasing i value
public void advancenext (View view) {
if (i>5) {
Intent intent = new Intent(Prompt1.this, Prompt2.class);
Prompt1.this.startActivity(intent);
}
}
}
return true;
}
});
}
I would do this
public class Prompt1 extends Activity implements OnTouchListener{
int i; //Variable i stores the touch number
float[] X, Y; //Array that will store the touchpoints
int ultscore1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prompt1);
i=1;
touchLayout.setOnTouchListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent event){
i++; //increasing i value
advancenext(v);
return true;
}
public void advancenext (View view) {
if (i>5) {
Intent intent = new Intent(Prompt1.this, Prompt2.class);
Prompt1.this.startActivity(intent);
}
}
}
This allows your class to directly handle the touch event (and any other touch events for views contained in the classes set content view) by just adding the on touch listener to the view. You can handle the incrementing of your variable i in onTouch like you were and call your advancenext method with the view passed to onTouch. The method, advancenext, could very easily have its functionality moved to onTouch, that is
#Override
public boolean onTouch(View v, MotionEvent event){
i++; //increasing i value
if (i>5) {
Intent intent = new Intent(Prompt1.this, Prompt2.class);
Prompt1.this.startActivity(intent);
}
return true;
}
But moving the functionality out of onTouch into it's own method will allow you to use advancenext with other io events (like onClick).
You have to evaluate your if statement inside your function. Be sure you have access to i variable.
public void advancenext(View view) {
if (i>5) {
Intent intent = new Intent(Prompt1.this, Prompt2.class);
Prompt1.this.startActivity(intent);
}
}
You've got your statement backwards:
public void advancenext (View view) {
if (i>5) {
Intent intent = new Intent(Prompt1.this, Prompt2.class);
Prompt1.this.startActivity(intent);
}
}
You should call your onClick() function no matter what, THEN check the condition. The way you have it now, you are ignoring the if statement completely.

Clear text in EditText when entered [duplicate]

This question already has answers here:
Why does my Android app crash with a NullPointerException when initializing a variable with findViewById(R.id.******) at the beginning of the class?
(9 answers)
Android setOnClickListener method - How does it work?
(5 answers)
Closed 1 year ago.
I'm trying to set and onclicklistener so that when I click within the edittext element it will clear its current contents. Is there something wrong here? When I compile this code I get a force quit and ActivityManager: Can't dispatch DDM chunk 4d505251: no handler defined error.
public class Project extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText editText = (EditText)findViewById(R.id.editText1);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
editText.setOnClickListener(this);
setContentView(R.layout.main);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText.setText("");
}
}
Also you can use code below
editText.getText().clear();
First you need to call setContentView(R.layout.main) then all other initialization.
Please try below Code.
public class Trackfolio extends Activity implements OnClickListener {
/** Called when the activity is first created. */
public EditText editText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.editText1);
editText.setOnClickListener(this);
}
#Override
public void onClick(View v) {
editText.getText().clear(); //or you can use editText.setText("");
}
}
just use the android:hint attribute in your EditText. This text shows up when the box is empty and not focused, but disappears upon selecting the EditText box.
We can clear EditText data in two ways
First One setting EditText is empty like below line
editext.setText("");
Second one clearing EditText data like this
editText.getText().clear();
I suggest second way
Your code should be:
public class Project extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText editText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText)findViewById(R.id.editText1);
editText.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == editText) {
editText.setText("");
}
}
}
For Kotlin:
Create two extensions, one for EditText and one for TextView
EditText:
fun EditText.clear() { text.clear() }
TextView:
fun TextView.clear() { text = "" }
and use it like
myEditText.clear()
myTextView.clear()
public EditText editField;
public Button clear = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_layout);
this. editField = (EditText)findViewById(R.id.userName);
this.clear = (Button) findViewById(R.id.clear_button);
this.editField.setOnClickListener(this);
this.clear.setOnClickListener(this);
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.clear_button){
//setText will remove all text that is written by someone
editField.setText("");
}
}
Very Simple to clear editText values.when u click button then only follow 1 line code.
Inside button or anywhere u want.Only use this
editText.setText("");
package com.example.sampleproject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class SampleProject extends Activity {
EditText mSearchpeople;
Button mCancel , msearchclose;
ImageView mprofile, mContact, mcalender, mConnection, mGroup , mFollowup , msetting , mAddacard;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
mSearchpeople = (EditText)findViewById(R.id.editText1);
mCancel = (Button)findViewById(R.id.button2);
msearchclose = (Button)findViewById(R.id.button1);
mprofile = (ImageView)findViewById(R.id.imageView1);
mContact = (ImageView)findViewById(R.id.imageView2);
mcalender = (ImageView)findViewById(R.id.imageView3);
mConnection = (ImageView)findViewById(R.id.imageView4);
mGroup = (ImageView)findViewById(R.id.imageView5);
mFollowup = (ImageView)findViewById(R.id.imageView6);
msetting = (ImageView)findViewById(R.id.imageView7);
mAddacard = (ImageView)findViewById(R.id.imageView8);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mSearchpeople.clearFocus();
}
});
}
}
i don't know what mistakes i did while implementing the above solutions, bt they were unsuccessful for me
txtDeck.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
txtDeck.setText("");
}
});
This works for me,
//To clear When Clear Button is Clicked
firstName = (EditText) findViewById(R.id.firstName);
clear = (Button) findViewById(R.id.clearsearchSubmit);
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.clearsearchSubmit);
firstName.setText("");
}
});
This will help to clear the wrong keywords that you have typed in so instead of pressing backspace again and again you can simply click the button to clear everything.It Worked For me. Hope It Helps
final EditText childItem = (EditText) convertView.findViewById(R.id.child_item);
childItem.setHint(cellData);
childItem.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
//Log.d("NNN", "Has focus " + hasFocus);
if (hasFocus) {
Toast.makeText(ctx.getApplicationContext(), "got the focus", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ctx.getApplicationContext(),
"loss the focus", Toast.LENGTH_SHORT).show();
}
return;
});
by setting Empty string you can clear your edittext
editext.setText("");
If the use of EditText is not mandatory, you can implement this behavior easily with the new material components:
<com.google.android.material.textfield.TextInputLayout
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint_field"
app:endIconDrawable="#drawable/ic_close_black_24dp"
app:endIconMode="clear_text"
app:endIconTint="#color/black">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint_value"
android:maxLines="1"
android:text="#{itemModel.value}" />
</com.google.android.material.textfield.TextInputLayout>
You only have to specify the drawable you want for the button that will clear the text and the action that it will execute. To clear the text, you can use iconMode="clear_text", but also "password_toggle" is available.
In XML you can write like:
<EditText
android:id="#+id/txtsearch"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_weight="1"
android:background="#drawable/roundlayoutbutton1"
android:ems="10"
android:gravity="center"
android:inputType="text"
android:textAllCaps="true"
android:text="search_xxxx"
android:textColor="#color/colorPrimaryDark"
android:visibility="visible" />
and in java class you may have below one :
EditText searchHost;
OnCreate() you write:
searchHost=findViewById(R.id.txtsearch);
searchHost.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(searchHost.getText().toString().equalsIgnoreCase("search_xxxx")){
searchHost.setText("");
Toast.makeText(getApplicationContext(),"Enter you text xxx...", Toast.LENGTH_LONG).show();
}
}
});
It works fine for me.
You can use the 'android:hint' attribute in your EditText also from code:
editText.setHint(CharSequence hint / int resid);
Then you don't need any onClickListener or similar. But consider that the hint value won't be passed. The editText will be stayed empty. In this case you can set your editText with your deflault value:
if(editText.getText().toString().equals("")) {
...use your default value instead of the editText... }
It's simple: declare the widget variables (editText, textView, button etc.) in class but initialize it in onCreate after setContentView.
The problem is when you try to access a widget of a layout first you have to declare the layout. Declaring the layout is setContentView.
And when you initialize the widget variable via findViewById you are accessing the id of the widget in the main layout in the setContentView.
I hope you get it!
I am not sure if your searching for this one
{
<EditText
.
.
android:hint="Please enter your name here">
}

Categories

Resources