【问题标题】:Making a layout clickable, and start an intent使布局可点击,并启动意图
【发布时间】:2015-08-21 13:05:30
【问题描述】:

我想让我的布局可点击,虽然这很容易,但我偶然发现了一些问题。这是我的 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);
}

当我运行应用程序并按下布局时,它崩溃了,我得到一个非法状态异常。

我的日志:

 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]

我做错了什么?

【问题讨论】:

  • 发布你的整个 xml
  • 它现在包括最重要的部分
  • 你也可以发布堆栈跟踪吗?
  • 什么是堆栈跟踪?

标签: java android xml exception android-intent


【解决方案1】:

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

【讨论】:

  • 尝试使用子RelativeLayout..在您的代码中这是父RelativeLayout..所以在里面添加另一个RelativeLayout然后尝试
  • 我没有包含我的整个 xml 代码,这已经是一个子相对布局
【解决方案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);
        }
       });
     }

【讨论】:

  • 当我将 .this 更改为 thenameofmyactivity.this “thenameofmyactivity” 变为红色。我必须先对其进行一些初始化吗?
  • 除了YourActivity你还能写什么是getApplicationContext()
  • 这样写:“getApplicationContext(), some.class” 确实运行了,但是当我按下布局时仍然崩溃
  • 谢谢 1.7*10^948370 老兄。
  • 千里眼;没有足够的声誉来投票,但如果你投票我的问题,我将能够尽快投票给你的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多