I'm trying to code an onClickevent button on screen 1 that makes
a spinner visible or invisible, depends of the needs, on screen 2 as a result.
Knowing that on screen 1 there are several buttons which uses the same views
or widgets on the second screen, I was thinking about it to use one screen for
all these activities.
It would be nice if someone knows and explain to me how to solve this problem.
I will attach the java code just to look at it.
public class screen1 extends Activity {
private View spinner1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.screen1);
spinner1 = findViewById(R.id.spinner1);
Button A = (Button) findViewById(R.id.b_A);
// error output: Cannot instantiate the type View.OnClickListener
A.setOnClickListener(new View.OnClickListener());
A.setOnClickListener(mVisibleListener);
}
#Override
// error output behind the line 'public void':The method onClick(View) of type screen1 must override or implement a supertype method
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("com.jack.test.SCREENMENU"));
}
OnClickListener mVisibleListener = new OnClickListener(){
public void onClick(View v){
spinner1.setVisibility(View.VISIBLE);{
};
// the rest is ok from here to down.
You seem to have some major glitches going on with the code in addition to what you are asking. Fortunately, if I understand you correctly, the thing you want is easy to fix:
#Override
public void onClick(DialogInterface dialog, int which)
{
if (need_is_met)
{
if (spinner1.getVisibility() == View.INVISIBLE)
view.setVisibility(View.VISIBLE);
else
view.setVisibility(View.INVISIBLE);
}
}
need_is_met is a boolean ... thats as far as i could get with your statement "depends of the needs"
as far as the rest of your code, it should read like this:
public class screen1 extends Activity
{
private View spinner1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
boolean need_is_met = true; // you can change this or have it set based on something later if you want
spinnerAutomerk = findViewById(R.id.spinnerAutomerk);
button_A = (Button) findViewById(R.id.b_A);
button_A.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (need_is_met)
{
if (spinnerAutomerk.getVisibility() == View.INVISIBLE)
spinnerAutomerk.setVisibility(View.VISIBLE);
else
spinnerAutomerk.setVisibility(View.INVISIBLE);
}
}
}
}
}
something like that. i took out all the requestWindowFeature, windowFlag etc because it is much neater to put this into your manifest:
...
<application
android:icon="#drawable/icon"
android:label="#string/app_name"
>
<activity
android:name=".Screen1"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen"
...
that last line, the theme bit, will set you up with any one of a number of themes (such as dark, light, transparent etc. just got to R.style and ctrl-F for theme and youll see there is a number to choose from. similar to this they can kill the title and notification bar, if you wish.
also i didnt to set net_is_met to something because i dont know what the rest of your code is about.
First off all you need to have screen2 as another activity if you want it to open when clicked and show the spinner (not sure if that is exactly what you meant).
You should use intents to switch to screen2's activity. There a billion examples on how to do that if you google it.
You would use a Boolean to check if certain requirements are met or not:
Boolean Reqs = false;
If(req_met){
Reqs = true;
} else {
Reqs = false;
}
Use that type of format then check if Reqs is true or not when sending the intent to see if the spinner is visible or not (I would use another intent for that)
Related
I wanted to ask what was the significance of creating a switch statement when implementing the onClickListener interface for multiple buttons. Like, we're already calling the setOnClickListener for that particular button by saying button_name.setOnClickListener()
So what's the point of specifying the id's again in the switch statement ? Why is it necessary to do so ? doesn't the point of doing button_name.setOnClickListener() mean - "do what's in here for this button" ?
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
// So we will make
switch (v.getId() /*to get clicked view id**/) {
case R.id.corky:
// do something when the corky is clicked
break;
case R.id.corky2:
// do something when the corky2 is clicked
break;
case R.id.corky3:
// do something when the corky3 is clicked
break;
default:
break;
}
}
}
What I'm trying to ask is, doing button2.setOnCLickListener() means - "Do what's set by this function for button2" right ? if not then what is the actual purpose/function performed by setOnClickListener() ?
Since you have set clickListeners to 3 different buttons, the method
....onClick(View v){.....
is going to get called when you click any of those 3 buttons. If you click the button1 you do not want to perform task actually assigned for button3. So to check and find out which button was pressed the switch statement is necessary.
Alternatively you could have done this:
corkyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// do something when the corky is clicked
}
});
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// do something when the play is clicked
}
});
so on and so forth...
This way you don't need a switch statement as in this case you know which button is being clicked on, AS you're setting the clickListener AND ALSO specifiying what you wanna do there itself.
It's more of a clean look, a more readable code style structure. If you have multiple widgets who need click listener, by implementing View.OnClickListener interface
and overriding onClick gives a cleaner look.
and inside onClick(View view){
- you can also use if statement but when the number of widgets is more
then it becomes messy, that's why we use switch statement to look cleaner.
}
and
btn.setOnClickListener(this)
// telling the button to pass the interface
so that overridden onClick can listen to this.
But If you don't want that or you have only one widget for click
then just use this, no need to implement and override.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
I have an app that consists of 3 Activities
MainActivity
CalculatorActivity
InformationActivity
My MainActivity has a confirm button that onClick starts the CalculatorActivity and everything is done correct and working as intended.
CalculatorActivity has 2 buttons, one calculateButton that checks something and shows a message and a learnMorebutton that starts the InformationActivity.
When I am on the
CalculatorActivity for the first time everything is fine and working.Pressing the learnMoreButton navigates me to the InformationActivity.That activity looks like this :
InformationActivity:
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switchActivity();
}
});
}
public void switchActivity(){
final Intent intentObj = new Intent(this,CalculatorActivity.class);
startActivity(intentObj);
}
A goBack button that gets me back to CalculatorActivity.Going back seems to break the functionality.Although the layout is there and everything looks as it should be, pressing the buttons (calculateButton,learnMoreButton) does nothing.
CalculatorActivity :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
final Button calculateButton = (Button) findViewById(R.id.calculateId);
final Button learnMoreButton = (Button) findViewById(R.id.learnMoreButtonId);
there are some more TextView and EditText that dont show up here but you get the point.Some more methods that do the calculations ,getters and setters.
This method
public void switchActivity(){
final Intent intentObj = new Intent(this,Information_activity.class);
startActivity(intentObj);
}
But I am not using onResume() , onPause() or any methods from the lifecycle apart from onCreate().
From some search that I have done I found out that I am doing something wrong with how I manage the activity lifecycle but I still can't find the solution.The dev documents didn't help me that much and a post with kinda the same problem as mine is old.
My question is, how the navigation from InformationActivity to CalculatorActivity should be done, so the functionality doesn't break when CalculatorActivity comes back to interact with the user.Which method should be called onResume()? , onRestart()? and how should it look like?
Thanks anyone who is willing to help.
P.S: As I mentioned , I have read the documents for the lifecycle of an Activity but I haven't found the solution.
instead of starting new activity everytime, finish the informationactivity.
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
You are creating too much activities moving going back and forth this way. You can use either destroy the activity with finish(); or you can also go back to previous activity using onBackPressed();
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
Try this out
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InformationActivity.this.finish();
}
});
}
Instead of saying where to go back, you can just finish the activity and it will automatically switch you to the previous one.
I think your activities are hierarchical thus you should be able to do the following from your main calculator activity:
Intent i = new Intent(this, InformationActivity.class);
startActivityForResult(i);
Your back button add this code:
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setResult(Result.OK);
finish();
}
});
You are all suggesting the same thing.Adding
Information_Activity.this.finish()
fixed the broken functionality , though you are all correct I can pick only one answer.
Thanks
I am very new to Andriod Programming and this is probably very basic question.
In my Application, the first page contains just button (for simplicity) login button.
After the user clicks login button it displays the toast and then I need to navigate to new class(page B) where I want to connect to a specific health sensor.
Problem
1. I tried implementing the just the basic part with onClickListener for button and then when clicked, go to next page, where enable Bluetooth,etc. I could not get to next page
MainActivity.java :
public class MainActivity extends AppCompatActivity {
Button button;
PollingTest pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"Logged In",Toast.LENGTH_SHORT).show();
pd = new PollingTest();
pd.call();
}
});
}
}
Second Page (Where wanted to Control BT). Never got to this page while testing on the tablet: -
For now just included if I could get a Toast atleast from this page: -
public class PollingTest extends Activity {
BluetoothAdapter btAdapter;
Button btn2;
protected void call() {
//super.onCreate(savedInstanceState);
//setContentView(R.layout.pairinglistactivity);
btn2 = (Button)findViewById(R.id.pollB);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG).show();
}
});
}
}
Here app crashes after clicking on Login button in first page.
I have actually got some different errors with different code, I was not able to make proper Toast or turn BT on in the second page as it was trying them in static method.( very Confusing:( )
Please help me. I know this v v basic Q..
EDIT:
Sorry, this Q is already answered here: -
Moving from one activity to another Activity in Android
You don't start an activity by instantiating it like a normal Java class. So this is wrong
pd = new PollingTest();
pd.call();
you should be using an Intent
and follow the Activity Lifecycle
so you would want something like
Intent i = new Intent(MainActivity.this, PollingTest.class);
startActivity(i);
then override onCreate() in PollingTest.java and put what is in call() in there or call that method from onCreate().
Also, a Toast should use Activity Context
I have a game quiz, and if a user's answer is wrong a popup screen pops up and stays on screen for 3 seconds. I do this with Handler. Since the game is time limited, they come up with solution to press back button to remove popup from the screen :) and move along. So I disabled the back button for that popup activity. BUT, now I have another problem. It seems that my Handler count time from the last click, so if I click back button on that popup screen Handler count time from that click. If I click it again, it starts from beggining. I've tried to click it 10-12 times and my popup screen was on for half a minute. :) And that's not good. How to make my popup be on for 3 seconds no metter if click back button or not during his time on?
My popup class:
public class WrongAnswer extends Activity{
TextView wrong;
String correctAnswer, correct;
public final int delayTime = 3000;
private Handler myHandler = new Handler();
public void onUserInteraction(){
myHandler.removeCallbacks(closePopup);
myHandler.postDelayed(closePopup, delayTime);
}
private Runnable closePopup = new Runnable(){
public void run(){
finish();
}
};
#Override
public void onBackPressed() {
//do nothing
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.wrong);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
correct = extras.getString("correctAnswer");
}
inicijalizujVarijable();
myHandler.postDelayed(closePopup, delayTime);
}
private void inicijalizujVarijable() {
wrong = (TextView) findViewById(R.id.tvWrong);
Typeface pogresanFont = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
wrong.setTypeface(pogresanFont);
Wrong.setText("Wrong answer!\nCorrect answer is:\n\n" + correct);
}
}
Remove this:
public void onUserInteraction(){
myHandler.removeCallbacks(closePopup);
myHandler.postDelayed(closePopup, delayTime);
}
It's resetting your handler on any interaction, which results in the behaviour you describe.
As a side note, it seems rather heavy to dedicate an Activity to this functionality, I think you'd be better off using a Dialog or similar.
You can show popup as Dialog and setCancelable() to false.
http://developer.android.com/reference/android/app/Dialog.html#setCancelable(boolean)
I am going nuts over this.
I did not find any working solution (tried a few from stackoverflow)
Scenario (this is an actual screenshot what is already done):
I have a Activity that has a View as his Attribute.
This view adds another view via View.addView(myView).
I now want to add a Button to myView (to be specific: after MotionEvent.ACTION_UP the button should appear in the right lower corner (this will start the robot to drive the track))
Here is a shortcut of my code:
public class ModeRouting extends View {
public ModeRouting(Context context) {
super(context);
Button asuroStartButton = new Button(context) //does not work
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int actionevent = event.getAction();
if (actionevent == MotionEvent.ACTION_UP
|| actionevent == MotionEvent.ACTION_CANCEL) {
asuroStartButton.visible=true;
view.add(asuroStartButton);
}
return true;
}
}
and my Activity:
//in constructor
contentView = (FrameLayout) findViewById(R.id.content);
onClickListenerFacade(routingMode, route);
//this removes all views from stack and places the new one on the view
private void onClickListenerFacade(View v, final View target) {
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
contentView.removeAllViews();
contentView.setBackgroundColor(0xff000000);
contentView.addView(target);
modeSelectorAnimation();
}
});
}
I tried to create a button in my mainactivity.xml and instantiate in my mainactivity.
I am missing some point in here but i am not sure which.
Since my view is purely dynamic (no layout.xml) i dont think i should use a layout.xml (maybe thats my mind-blockage) but instead set the button attributes dynamically too.
Any hint is appreciated!
You want to extend ViewGroup rather than just a View (LinearLayout, RelativeLayout, FrameLayout, etc) - they handle child views for you.
I think maybe you need to refresh the whole view/activity. Try to do this in the onResume methode, maybe this helps. But as you don't use a layout.xml, I'm not sure if this helps you much..
#Override
protected void onResume(){
super.onResume();
setContentView(R.layout.activity_main);
}