setOnClickListener无法正常工作

时间:2020-05-27 08:12:13

标签: android onclicklistener buttonclick

首先,我是android的新手。

我的应用程序中有三个活动。即 MainActivity,TC和navigation_drawer。

用户首先输入MainActivity,提供其姓名,然后单击按钮输入TC(工作正常)。 TC内部有两个按钮“同意”,“不同意”,如下所示。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TC">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/agree"
        android:text="Agree"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/not_agree"
        android:text="Do not Agree"
        android:layout_below="@id/agree"/>

</RelativeLayout>

现在,如果用户单击同意,则应转到导航抽屉;如果单击不同意,则应返回< strong> MainActivity 。它的代码是:

public class TC extends AppCompatActivity {

    private Button Agree, NotAgree;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_t_c);

        Agree = (Button) findViewById(R.id.agree);
        NotAgree = (Button) findViewById(R.id.not_agree);

        Agree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(TC.this, "Agree", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(TC.this, navigation_drawer.class);
                startActivity(intent);

            }
        });

        NotAgree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(TC.this, "Not Agree", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(TC.this, MainActivity.class);
                startActivity(intent);
            }
        });
    }
}

添加Toast只是为了检查是否调用了正确的方法(它正在调用正确的方法)

AndroidManifest.xml包含(我不确定这是否有帮助):

        <activity android:name=".TC" android:noHistory="true"/>
        <activity android:name=".navigation_drawer" />
        <activity
            android:name=".MainActivity"
            android:noHistory="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

问题是,由于某种原因,无论我单击哪个按钮,它总是都重定向到 navigation_drawer ,对于Toast消息显示的两个按钮也都按预期显示。 >

我不知道我在这里想念什么,请提出解决方案。谢谢。

2 个答案:

答案 0 :(得分:0)

我看不到您的代码有什么问题,应该可以正常工作,但似乎您在两次单击按钮时都开始了navigation_drawer活动。

因此,我建议您通过为每个Intent变量赋予不同的名称,例如setOnClickListner()Intent来声明并初始化intent1块外的两个按钮的intent2变量然后尝试再次运行。

答案 1 :(得分:0)

测试此:

删除android:noHistory="true"中的Manifest

并在startActivity(....)之后致电finish()

相关问题