简体   繁体   中英

onClickListener not working after setContentView

MainActivity

package com.Kevious.Kevin;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.view.View.*;
import android.opengl.*;
import android.content.*;
import android.text.*;
import java.net.*;

public class MainActivity extends Activity
{
String passw;
String value = "Test";
int i = 1;
TextView textView;
Button button;
EditText editText;


@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {

public void onClick(View p1)
{
loadMethod();

}

}
);

editText = (EditText) findViewById(R.id.editText);

editText.addTextChangedListener(new TextWatcher(){

public void beforeTextChanged(CharSequence p1, int p2, int p3, int p4)
{
}

public void onTextChanged(CharSequence p1, int p2, int p3, int p4)
{

// TODO: Implement this method

passw = editText.getText().toString();
textView.setText(passw);
passw = textView.getText().toString();
}

public void afterTextChanged(Editable p1)
{

}
}
);
}

public void loadMethod()
{
passwCheck();
}


public void passwCheck(){

passw = textView.getText().toString();

if (passw.equals("kev"))
{
Toast.makeText(this, "corrrect " + passw, Toast.LENGTH_SHORT).show();
setContentView(R.layout.nextactivity);
} else {
Toast.makeText(this, "incorrect " + passw, Toast.LENGTH_SHORT).show();
}
}
}

NextActivity

package com.Kevious.Kevin;
import android.os.*;
import android.content.*;
import android.app.*;
import android.widget.*;
import android.view.View.*;
import android.view.*;

public class NextActivity extends Activity
{
Button button2;
TextView textView2;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
textView2 = (TextView) findViewById(R.id.textView2);
textView2.setText("Welcome Kevin");
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener(){
public void onClick(View p1)
{
textView2.setText("button clicked");
buttonclick2();
}
}
);
}


public void buttonclick2(){


Toast.makeText(this, "logged out", Toast.LENGTH_SHORT).show();

setContentView(R.layout.main);
}
}

Im new to stackoverflow, so I hope I am creating this correctly. I apologize if I did it wrong.

I am learning Android Development and just experimenting and creating my first app and somehow I encountered a problem where one of my buttons do not work, even when I have added the button listeners correctly.

When I type "kev" as the password on the main layout and press the button, it will take me to NextActivity Layout via the "setContentView(.....)" this works fine.

The problem is, when I am in the NextActivity Screen, it will have a button. Somehow when I click on that button, it does nothing. I am sure the code is right. Can someone help me out here?

Thanks

setContentView() doesn't start a new Activity. To do that, run something like this:

Intent intent = new Intent(this, NextActivity.class);
startActivity(intent);

And run setContentView in the new Activity, and set any onClickListeners there.

Other than the answers posted. You are trying to initialize views without setting the content to the activity in NextActivity. You can findviewbyid of the views of the current view hierarchy set to the activity.

If you need to navigate from one activity to another say on button click

     startActivity(new Intent(ActivityName.this,NextActivity.class); or
     startActiivty(new Intent("packagename.NextActivity); 

setContentView. You have misunderstood the purpose of setContentView.

http://developer.android.com/reference/android/app/Activity.html#setContentView(int)

Set the activity content to an explicit view .

This view is placed directly into the activity's view hierarchy. It can itself be a complex view hierarchy. When calling this method, the layout parameters of the specified view are ignored. Both the width and the height of the view are set by default to MATCH_PARENT. To use your own layout parameters, invoke setContentView(android.view.View, android.view.ViewGroup.LayoutParams) instead.

Parameters

     view   The desired content to display.

In your NextActivity

      @Override 
      public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main); 
       // this should be first not in buttonclick2()
      textView2 = (TextView) findViewById(R.id.textView2);
       // then initialize views.  
      ...
      } 

Example:

  public class MainActivity extends Activity
 {
 String passw;
 TextView textView;
 Button button;
 EditText editText;


@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
editText = (EditText) findViewById(R.id.editText1);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View p1)
{
  passw = editText.getText().toString();
  if (passw.equals("kev"))
  {
  Toast.makeText(MainActivity.this, "corrrect " + passw, Toast.LENGTH_SHORT).show();
  startActivity(new Intent(MainActivity.this,NextActivity.class));
  } else {
  Toast.makeText(MainActivity.this, "incorrect " + passw, Toast.LENGTH_SHORT).show();
  }
}
});
}
}

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:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp"
    android:ems="10"
    android:inputType="textPassword" >

    <requestFocus />
</EditText>

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/editText1"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="83dp"
    android:text="Password" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="39dp"
    android:text="Button" />

</RelativeLayout>

NextActivity.java

public class NextActivity extends Activity
{
Button button2;
TextView textView2;
@Override 
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.next);
  textView2 = (TextView) findViewById(R.id.textView1);
  textView2.setText("Welcome Kevin");
  button2 = (Button) findViewById(R.id.button1);
  button2.setOnClickListener(new OnClickListener(){
  public void onClick(View p1)
  {
    textView2.setText("button clicked");
  }
  });
 }
 } 

next.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="TextView" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_alignParentBottom="true"
    android:text="Button" />

</RelativeLayout>

Manifest.xml

    <activity
        android:name="com.example.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
     <activity
        android:name="com.example.NextActivity"
        android:label="@string/app_name" >

    </activity>

Actually you are not navigating to the NextActivity. You are in the MainActivity itself, you have just changed the layout dynamically. For navigating to the NextActivity use,

startActivity(new Intent(MainActivity.this,NextActivity.class));

And in the onCreate() method of the NextActivity set your layout and try what you were trying to do.

Calling setContentView() multiple times in the same Activity is not recommended. See: Android: switching screens with new activity or just changing content view .

Also, you need to start NextActivity by something like:

Intent intent = new Intent(this, NextActivity.class);
startActivity(intent);

Right now, you're just changing the UI without adding the functionality of the Activity.

if (passw.equals("kev"))
{
Toast.makeText(this, "corrrect " + passw, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), NextActivity.class);
startActivity(intent);
} else {
Toast.makeText(this, "incorrect " + passw, Toast.LENGTH_SHORT).show();
}
}

Would you like to put something towards ur next activity use

Intent intent = new Intent(getApplicationContext(), NextActivity.class);
intent.putExtra("your_key", your_value);
intent.putExtra("your_next_key", your_next_value);
startActivity(intent);

AND DONT FORGET TO REGISTER BOTH YOUR ACTIVITIES IN YOUR MANIFEST! Make sure it is spelled like ur .java classes (case sensitive!)

AndroidManifest.xlm

  <application
        android:icon="@drawable/logo"
        android:label="@string/app_name" >
       <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".NextActivity" />
  </application>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM