TextView onClickListener无法正常工作

时间:2018-04-08 17:06:27

标签: java android onclick textview onclicklistener

我在MainActivity布局上单击TextView时尝试调用另一个布局。我尝试在XML文件上使用onClick(),但由于课程目的,它要求所有内容都是从Java文件处理的。以下是教师给出的示例代码,理论上应该可以工作,但事实并非如此,其次是我自己的代码。当我单击TextView以调用另一个布局时,程序崩溃。

我的MainActivity.java

package com.wanli.jorgemorales.additionalviews;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);

        TextView numbers = (TextView) findViewById(R.id.numbers);
        TextView family = (TextView) findViewById(R.id.family);
        TextView colors = (TextView) findViewById(R.id.colors);
        TextView phrases = (TextView) findViewById(R.id.phrases);

        numbers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, Numbers.class);
                startActivity(intent);
            }
        });


    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用以下属性在xml中设置单击处理程序:

android:clickable="true"

不要忘记clickable属性,如果没有它,则不会调用click处理程序。

main.xml中

...

<TextView 
   android:id="@+id/numbers"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"               
   android:text="Click Me"
   android:textSize="55sp"                
   android:clickable="true"/> <!--Do not forget this attribute-->
...

MyActivity.java

// Find the View that shows the numbers category
TextView numbers = (TextView) findViewById(R.id.numbers);

// Set a click listener on that View
numbers.setOnClickListener(new View.OnClickListener() {
   // The code in this method will be executed when the numbers View is clicked on.
   @Override
   public void onClick(View view) {
       Intent numbersIntent = new Intent(MainActivity.this, NumbersActivity.class);
       startActivity(numbersIntent);
   }
});

答案 1 :(得分:0)

设置onClickListener的最简单方法是使用Button。按钮也可以保存文本。将XML文件中的TextView numbers更改为Button和java代码。

示例:

    Button numbers = (Button) findViewById(R.id.numbers); //Remember to change type in XML
    TextView family = (TextView) findViewById(R.id.family);
    TextView colors = (TextView) findViewById(R.id.colors);
    TextView phrases = (TextView) findViewById(R.id.phrases);

    numbers.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Numbers.class);
            startActivity(intent);
        }
    });

XML示例:

...
<Button
    android:id="@+id/numbers"
    ...
    android:text="Text"

/>
...