create one button and method [closed] - java

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am new in java or android just create one demo.
I found good example on google: https://github.com/rciovati/Android-KeyboardView-Example
Now I want to create one button and method in Java and on them I click the button and the method is invoked and will show a hello world message.
I need good help on this because I don't know where I want to change and where to put code for create button.

I am not sure about your problem but I assume you want to define click listener with method which prints Hello World message.
Include android:onClick attribute in your Button inside XML layout.
For example: android:onClick="btnHelloWorldClick"
Define method in Activity class with the same name given in android:onClick attribute.
For example:
public void btnHelloWorldClick(View v)
{
System.out.println("Hello world");
// or Toast.makeText(this, "Hello world", Toast.LENGTH_LONG).show();
}

Your code,
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), "Hello World", Toast.LENGTH_LONG).show();
}
});
and your layout,
<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=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="232dp"
android:text="Button" />
</RelativeLayout>

You can do:
First add attribute "android:onClick="btnHelloWorldClick"" in Button controller in xml layout.
For Example:

Define button in 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=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</RelativeLayout>
MainActivity.java
setContentView(R.id.activity_main);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// do something or call a function defined.
Toast.makeText(MainActivity.this, "Hello World", Toast.LENGTH_LONG).show();
}
});
Define onclick attribute for button in xml
activtiy_main
<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=".MainActivity" >
<Button
android:id="#+id/button1"
android:onClick="btnClick" // method
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</RelativeLayout>
MainActivity.java
public void btnClick(View v)
{
// do something
Toast.makeText(MainActivity.this, "Hello world", Toast.LENGTH_LONG).show();
}
To create a button programatically
MainActivity
setContentView(R.layout.activity_main);
RelativeLayout rl = (RelativeLayout)findViewById(R.id.relativelayout);
// Define relative layout in xml layout file.
Button b = new Button(MainActivity.this);
rl.addView(b);
// button click using annonymous inner class
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// do something or call a function defined.
Toast.makeText(MainActivity.this, "Hello World", Toast.LENGTH_LONG);
}
});
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/relativelayout"
android:layout_height="match_parent"
tools:context=".MainActivity" >
Your class can also implement OnClickListener. In that case
public class MainActivity extends Activity implements OnClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1)
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) //returns int
{
case R.id.button1 :
// do something or call a function defined.
Toast.makeText(MainActivity.this, "Hello World", Toast.LENGTH_LONG);
break;
}
}
}

Well this question is most likely to get closed but here's what you need to know
To handle the clicks for any view let it be a Relative layout,button,textview ,etc you need to implement the onClickListener and perform function inside the onclick function of the interface
there are many ways you can set onclick listeners:
1 Let you activity implement onclickListener it will ask you to implement onClick function and you can run your function there
public class HomeScreenActivity extends Activity implements OnClickListener {
public void onClick(View v) {
int clickedId = v.getId();
switch (clickedId) {
case R.id.nearbyButtonHome:
nearbyButtonAction();
break;
case R.id.cgExButtonHome:
cgExButtonAction();
break;
case R.id.styleButtonHome:
styleButtonAction();
break;
}
}
}
2 you can set the onclick listeners on button object directly
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dismiss();
}
});
3 you can add a attribute to button tag in layout file
android:onClick="func1"
and in your activity create this function.
this is all about the button clicks

Related

Android pass onClick to child

Hello my goal is to make my custom view (ViewCircleOfInterest.java) receiving onClick. Now every time I click onClickListener on ViewCircleOfInterest.java is not called.
My interesting part of layout looks like that:
my_layout.xml
<FrameLayout
android:id="#+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/rl"
android:layout_alignParentTop="true"
android:background="#bbb">
<abc.x.y.ViewCircleOfInterest
android:id="#+id/view_circle_of_interest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
I have FrameLayout on my layout and I added view (SurfaceView - CameraPreview.java) to it like that
MyActivity.java
rootView = findViewById(android.R.id.content).getRootView();
viewCircleOfInterest = rootView.findViewById(R.id.view_circle_of_interest);
viewCircleOfInterest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(NewWayMeasurementActivity.this, "circle a", Toast.LENGTH_SHORT).show();
}
});
(...)
((FrameLayout) rootView.findViewById(R.id.camera_view)).addView(cameraPreview);
(...)
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
On CameraPreview.java in my init() method I do like that:
(...)
viewCircleOfInterest = ((NewWayMeasurementActivity)activity).viewCircleOfInterest;
viewCircleOfInterest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "circle aa", Toast.LENGTH_SHORT).show();
}
});
I also set onClickListener on my ViewCircleOfInterest.java
public ViewCircleOfInterest(SurfaceView surfaceView) {
super(surfaceView.getContext());
this.surfaceView = surfaceView;
setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(surfaceView.getContext(), "circle aaa", Toast.LENGTH_SHORT).show();
}
But unfortunately non of this method works, I still cannot receive onclicks from my custom view. How to solve that? I hope my question and code is understandable.
Make these changes in your code and check if it works.
my_layout.xml
<FrameLayout
android:id="#+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/rl"
android:layout_alignParentTop="true"
android:background="#bbb">
<abc.x.y.ViewCircleOfInterest
android:id="#+id/view_circle_of_interest"
android:layout_width="wrap_content"
android:clickable="true"
android:layout_height="wrap_content"/>
</FrameLayout>
MyActivity.java
((FrameLayout)rootView.findViewById(R.id.camera_view)).addView(cameraPreview,0);
Here we are adding cameraPreview at 0 index so your custom view is on top now and that should receive clicks.

BottomSheetBehaviour is dissmised when user clicks on back

I have a BottomSheetBehaviour in my layout, and it works absolutely fine. The problem is, that whenever user clicks on back button, it becomes invisible(or gone). How can I prevent it to be non-dissmissable?
create a layout for your bottom sheet as:
<androidx.core.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="16dp"
app:behavior_peekHeight="260dp"//change according to your need
app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
//your design here
</LinearLayout>
</androidx.core.widget.NestedScrollView>
include this layout in your main layout file
<include layout="#layout/layout_name" />
now you can use your bottom sheet in your activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name);
View bottomSheet = findViewById(R.id.bottomSheet);
//add behaviour as
BottomSheetBehavior<View> bottomSheetBehavior =BottomSheetBehavior.from(bottomSheet);
//access your views inside bottomSheet as
TextView textView = bottomSheet.findViewById(R.id.textViewId);
}
Just override onCancel() or onDismiss().
#Override
public void onCancel(DialogInterface dialog) {
// super.onCancel(dialog); // comment this out
Toast.makeText(MainApp.get(), "CANCEL REQUESTED", Toast.LENGTH_SHORT).show();
}
Or override onBackPressed in onCreateDialog function when you're crating the dialog
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new Dialog(getActivity(), getTheme()){
#Override
public void onBackPressed() {
Toast.makeText(MainApp.get(), "CANCEL REQUESTED", Toast.LENGTH_SHORT).show();
}
};
}

How to set the content view of a Activity from another actvity

I am building an music player. Whenever the user will click on a ImageView, a dialog will come. The dialog will have a switch in it. I wanted to say that whenever the user switches on the switch to on, I wanted to change the ContentView of MainActivity.java to a custom layout file. How can I do that.
Any suggestions would be accepted..
Thanks
I would add a callback to your Dialog that you simply invoke to set your content, something like
class MyDialog(val switchChangedCallback: (Boolean) -> Unit) : DialogFragment() ...
When you change the switch, invoke the callback and handle the result in the Activity:
val dialog = MyDialog(switchChangedCallback = { isOn ->
if (isOn) {
setContentView(R.layout.abc)
} else {
setContentView(R.layout.def)
}
})
dialog.show(supportFragmentManager, MyDialog::class.java.name)
You may need to check that the callback survives app rotation!
You can try below code...
Dialogue :
Dialog dialogue = new Dialog(MainActivity.this);
dialogue.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogue.setCancelable(false);
dialogue.setContentView(R.layout.dialogue);
Switch mySwitch = (Switch) dialogue.findViewById(R.id.MYSWITCH);
Button btnClose = (Button) dialogue.findViewById(R.id.CLOSEBTN);
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
setContentView(R.layout.layout1);
}
else{
setContentView(R.layout.layout2);
}
}
});
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogue.dismiss();
}
});
dialogue.show();
dialogue.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="16dp"
android:orientation="vertical"
android:layout_height="match_parent">
<Switch
android:id="#+id/MYSWITCH"
android:text="Change Layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/CLOSEBTN"
android:text="Close"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
as your question says you need a switch inside dialogue , so we need to create a custom dialogue layout and apply it to dialogue !

Why does my app keep crashing when I have 2 setOnclickListener?

My app keeps crashing when I set 2 setOnclickListener. The interesting thing is, when I only have 1 button intent, it doesn't crash. When I have 2 buttons, the new button does not bring me to new screen, and the old one just crashes the whole app.
Here's my code for the "old" button:
SignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intSignUp=new Intent(LoginActivity.this,MainActivity.class);
startActivity(intSignUp);
}
});
If that's the only thing, then everything works. But when I add following, the new one doesn't work and old one crashes:
Support.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent support=new Intent(LoginActivity.this,Support.class);
startActivity(support);
}
});
Here's the Logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference.
at com.hoversfw.notes.LoginActivity.onCreate(LoginActivity.java:96)
And LoginActivity.java Line 96 is the beginning of Support.setOnclickListener.
Also, I have everything declared like:
Support=findViewById(R.id.Support);
SignUp=findViewById(R.id.textView);
Here's my XML file code:
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="Already have an account? Sign in!"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.505"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button" />
<Button
android:id="#+id/Support"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginEnd="29dp"
android:text="Support"
app:layout_constraintEnd_toStartOf="#+id/about"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
I also have all ID matched, Android Studio detects no error. I wonder what's causing the problem.
UPDATE
I have everything matched, like java file and xml, no ID is same, everything declared. And I don't think there is any problem with XML.
SignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intSignUp=new Intent(LoginActivity.this,MainActivity.class);
startActivity(intSignUp);
}
});
/*Support.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent support=new Intent(LoginActivity.this,Support.class);
startActivity(support);
}
});*/
If it's like above, then SignUp it works. If it's like
SignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intSignUp=new Intent(LoginActivity.this,MainActivity.class);
startActivity(intSignUp);
}
});
Support.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent support=new Intent(LoginActivity.this,Support.class);
startActivity(support);
}
});
Both of them doesn't work. (The difference is last one I commented Support.setOnClickListener..... but this one I made it as code.)
I can't confirm directly your error because you don't show your xml, but maybe you can do it.
you need check id view in xml same with you call in activiy with findViewById()
findViewById must above in your listener
If you are using 2 buttons, then you need to link them as button for both of them.
UPDATED
Since, you are using button and textview. I updated the answer.
This code at xml
<?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"
tools:context=".Main2Activity">
<TextView
android:id="#+id/txtViewSupport"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Support" />
<Button
android:id="#+id/btnSignUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SignUp" />
</LinearLayout>
This code at Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button buttonSignUp = findViewById(R.id.btnSignUp);
TextView textViewSupport = findViewById(R.id.txtViewSupport);
buttonSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
textViewSupport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}

Toggle visibility of a layout on onClick

I need to set this layout visible when i click a button, my java is like:
Layout propLayout = (Layout) findViewById(R.id.properLayout);
public void propsBtn(View view) {
propLayout.setVisiblity(View.Visible);
}
I know I'm totally wrong with the layout line! I'll be very grateful if someone could show me how to set it right :)
This is my XML:
<FrameLayout 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:background="#color/mainBackGround"
tools:context="com.myapplication2.app.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp">
...contents...
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:id="#+id/properLayout">
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_gravity="bottom"
android:padding="8dp">
...contents...
</RelativeLayout>
</LinearLayout>
DerGolem gave the right answer but he then deleted it, so I report it here now:
//First we set visibility value of interested layout either to gone, visible or invisible
android:visibility="gone"
Then under onCreate write like:
//specify the button that has to handle visibility
ImageButton properties = (ImageButton) findViewById(R.id.propBtn);
//And the layout we want to change is visibility
final LinearLayout propLayout = (LinearLayout) findViewById(R.id.properLayout);
properties.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (propLayout.getVisibility() == View.VISIBLE){
propLayout.setVisibility(View.INVISIBLE);
} else {
propLayout.setVisibility(View.VISIBLE);
}
}
});
The another way of toggle, with less lines, if someone likes
// button to click
ImageButton properties = (ImageButton) findViewById(R.id.propBtn);
// and LinearLayout to toggle
final LinearLayout propLayout = (LinearLayout) findViewById(R.id.properLayout);
properties.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
propLayout.setVisibility((propLayout.getVisibility() == View.VISIBLE)
? View.INVISIBLE
: View.VISIBLE);
}
});
You will need to set an OnClickListener() on the layout you want to toggle. Then inside the listener you check to see if the layout is visible or not. If it is, then you set its visibility to View.INVISIBLE. Otherwise, you set it to View.VISIBLE.
Try this:
int counter = 0;
TextVeiw tv = (TextView) findViewById(R.id.textView);
Button button = (Button ) findViewById(R.id.but);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
if(counter%2==0){
tv.setVisibility(View.Visible);//show
} else {
tv.setVisibility(View.Gone);//hide
}
}
});

Categories