gpt4 book ai didi

可点击 TextView 的 Android 问题

转载 作者:行者123 更新时间:2023-11-29 00:22:15 25 4
gpt4 key购买 nike

我有一个 fragment 和带有两个 TextView 的 LinearLayout。当我点击 LinearLayout 时,我想做点什么。但是我的应用程序崩溃了。

这是我的 Java 类:

public class MyClass extends Fragment implements LocationListener {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";

public NejblizsiBary() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);

return rootView;
}

public void detaily(View v){


}

这是我的 XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity$DummySectionFragment" >

<TextView
android:id="@+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

<LinearLayout
android:id="@+id/ll"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffdf33"
android:clickable="true"
android:focusable="true"
android:onClick="detaily"
android:orientation="horizontal" >
<TextView
android:id="@+id/nazev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:duplicateParentState="true"
android:text="Restaurace u Androida"
android:textColor="#000000"
android:textSize="40sp"
android:textStyle="normal" />

<TextView
android:id="@+id/adresa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10sp"
android:duplicateParentState="true"
android:text="Imaginární 12"
android:textColor="#000000"
android:textSize="20sp"
android:textStyle="normal" />
</LinearLayout>
</RelativeLayout>

最佳答案

是的,如果您使用 android:onClick 属性并在 fragment 类中定义方法,它会导致崩溃。

最终的原因是因为 android:onClick 是通过在 View 的 Context 上查找方法来实现的,这(通常)将是您的 Activity。 View 没有 fragment 的概念,因此它们无法在 fragment 上找到方法或知道它们应该查看哪个 fragment 。

解决方案:

有两种可能的解决方案:

  1. 定义一个点击监听器并将其设置到 LinearLayout 中。
  2. 在要替换 fragment 的 Activity 中定义一个方法。

关于可点击 TextView 的 Android 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22335389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com