简体   繁体   中英

OnClickListener on second button is neither initialized properly nor working as expected

I have 2 buttons and 2 separate activities and I want control flow like this :

  • Activityone
  • buttonOneActivityTwo
  • buttonTwoActivityThree

main.xml:

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

<LinearLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_weight="1.0">

    <LinearLayout
        android:layout_height="50dp"
        android:layout_width="match_parent"
        android:orientation="horizontal">

        <Button
            android:layout_height="match_parent"
            android:layout_width="50dp"
            android:background="@drawable/rozmare"/>

        <TextView
            android:layout_height="match_parent"
            android:text="کار های روزمره"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_width="match_parent"
            android:gravity="center"
            android:textSize="25sp"/>

    </LinearLayout>

    <EditText
        android:textSize="20.0sp"
        android:gravity="top|right"
        android:id="@+id/editText1"
        android:padding="5.0dip"
        android:scrollbars="vertical"
        android:fadingEdge="vertical"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:text=""
        android:capitalize="sentences"
        android:layout_gravity="top|right"
        android:textColor="#000000"
        android:background="#FFFFFF"/>

</LinearLayout>

<LinearLayout
    android:layout_height="match_parent"
    android:layout_width="65dp"
    android:orientation="vertical"
    android:layout_margin="1dp">

    <ScrollView
        android:layout_height="match_parent"
        android:layout_width="match_parent">

        <LinearLayout
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:orientation="vertical">

            <Button
                android:layout_height="65dp"
                android:layout_width="match_parent"
                android:id="@+id/notelist"
                android:background="@drawable/personal"
                android:layout_margin="1dp"/>

            <Button
                android:layout_height="65dp"
                android:layout_width="match_parent"
                android:background="@drawable/kasbokar"
                android:layout_margin="1dp"
                android:id="@+id/notelist1"/>

        </LinearLayout>

    </ScrollView>

</LinearLayout>

</LinearLayout>

MainActivity.java

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Menu;
import android.widget.TextView;
import android.widget.EditText;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class MainActivity extends Activity {

Button buttonOne;
Button buttonTwo;
EditText editText1;
String fileName;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    addListenerOnButton();
    getActionBar().hide();
    getWindow().setSoftInputMode(3);
    editText1 = (EditText) findViewById(R.id.editText1);
    fileName = getResources().getString(R.string.file_name);
    try {
        FileInputStream fis = openFileInput(fileName);
        byte[] readBytes = new byte[fis.available()];
        fis.read(readBytes);
        editText1.setText(new String(readBytes));
        fis.close();
    } catch (Exception e) {
        return;
    }
}

public void onPause() {
    super.onPause();
    try {
        FileOutputStream fos = openFileOutput(fileName, 0);
        fos.write(editText1.getText().toString().getBytes());
        fos.close();
    } catch (Exception e) {
        return;
    }
}

public void addListenerOnButton() {

    final Context context = this;

    buttonOne = (Button) findViewById(R.id.notelist);

    buttonOne.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent intent = new Intent(context, NoteList.class);
                startActivity(intent);


    buttonTwo = (Button) findViewById(R.id.notelist1);

    buttonTwo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent intent = new Intent(context, NoteList1.class);
            startActivity(intent);

            }

        });

}



});}

public void EXIT(View view) 
{
    finish();
}}

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.whitegate.noteking"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="16" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <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=".NoteList"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustUnspecified"/>

    <activity 
        android:name=".NoteEdit"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustUnspecified"/>

    <activity
        android:name=".NoteList1"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustUnspecified"/>

    <activity 
        android:name=".NoteEdit1"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustUnspecified"/>
</application>

But both buttons are doing the same action, both of them are going to activityTwo and the other issue is, If i don't touch the ButtonOne the ButtonTwo will not work.

You have added the listener of second button inside the listener of first button so

If i dont touch the ButtonOne the ButtonTwo will not work.

  • listener of second button only be initialize when you press the first button

    but they should be separate

     public void addListenerOnButton() { final Context context = this; buttonOne = (Button) findViewById(R.id.notelist); buttonOne.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, NoteList.class); startActivity(intent); } }); buttonTwo = (Button) findViewById(R.id.notelist1); buttonTwo.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, NoteList1.class); startActivity(intent); } }); } 

both of them are going to activityTwo

This behavior is related to simply using the same layout structure so use settext function or make changes in XML code.

A solution to your issue would be to define the onClick functions in your xml

<Button
android:text="Don't have an account? Join!"
android:onClick="toRegister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

Then define your function in your class

    public void toRegister(View view){

    Intent newIntent = new Intent(this, SignUpActivity.class);
    newIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    LoginActivity.this.startActivity(newIntent);
}

You have added second listener in first listener.

buttonOne.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

    Intent intent = new Intent(context, NoteList.class);
    startActivity(intent);


    buttonTwo = (Button) findViewById(R.id.notelist1);

    // >>>>>>>>>>>>>>>>>>>>>>> inside buttonOne
    buttonTwo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent intent = new Intent(context, NoteList1.class);
            startActivity(intent);

        }

    });
    // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

}
}); //  >>>>>>>>>> button one ends here

Another easy way to declare your onClickListener is to declare it as an object field like below

  private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.notelist1: {
                    // go to notelist 1
                    break;
                }

                case R.id.notelist: {
                    // go to notelist 
                    break;
                }
            }
        }
    };

And set listeners on buttons like below

buttonOne.setOnClickListener(clickListener);
buttonTwo.setOnClickListener(clickListener);

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