使布局可单击,并启动意图

时间:2015-06-06 17:50:32

标签: java android xml exception android-intent

我想让我的布局可点击,我觉得这很容易,但我偶然发现了一些问题。这是我的xml代码:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#0D47A1"
    android:id="@+id/mylayout"
    android:clickable="true"
    android:onClick="layout">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="sometext"/>

</RelativeLayout>

和Java代码:

public void layout (View view){
    Intent myintent = new Intent(this, some.class);
    startActivity(myintent);
}

当我运行应用程序并按下布局时,它会崩溃,并且我会收到非法状态异常。

我的logcat:

 java.lang.IllegalStateException: Could not find a method layout(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.RelativeLayout with id 'mylayout'

Caused by: java.lang.NoSuchMethodException: layout [class android.view.View]

我做错了什么?

2 个答案:

答案 0 :(得分:2)

执行xml中的更改,如下面的代码:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#0D47A1"
    android:id="@+id/mylayout">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="sometext"/>

</RelativeLayout>

在你的活动中

    RelativeLayout relativeLayout;

public class YourActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.NameOfLayout);

        relativeLayout = (RelativeLayout)findViewById(R.id.mylayout);

        relativeLayout.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
         Intent myintent = new Intent(getApplicationContext(), some.class);
         startActivity(myintent);
        }
       });
     }

答案 1 :(得分:0)

删除“查看视图”并更改方法名称“布局”。因为它提到默认值,所以提到Xml布局..