如何在片段中使用按钮打开一个新的活动?

huangapple go评论62阅读模式
英文:

How can I open a new activity using a button in a fragment?

问题

我试图从一个片段移动到一个活动,但每当按下按钮时,我的程序就会崩溃。我似乎找不到错误的源头。

我已经尝试以许多方式更改意图语句,但每次程序仍然崩溃,而且我没有得到任何关于错误的详细信息。

public void Imagebuttonclicked(View view) {

    for (int i = 0; i < newArray.length; i++) {

        if (view.getId() == newArray[i]) {
            int value = i + 1;
            Log.i("FIRST", String.valueOf(value));
            Intent intent = new Intent(getActivity(), tutorialActivity.class);
            getActivity().startActivity(intent);
        }
    }

}
英文:

I'm trying to move from a fragment to an activity with a button, but every the button is pressed my program crashes. I can't seem to find the source of the error.

I have tried changing the intent statement in many ways but each time the program still crashes, and I'm not being given any details on the error.

public class ExercisesFragment extends Fragment {

    int[] newArray;
    
    private FragmentExercisesBinding binding;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentExercisesBinding.inflate(getLayoutInflater(), container, false);
        View view = binding.getRoot();
    
        newArray = new int[]{
    
              R.id.barbellRow, R.id.barbellFrontSquat, R.id.barbellShrugs, R.id.bodyweightSquat, R.id.dumbbellChestPress,
                R.id.lateralRaise, R.id.overheadTricepExtensions, R.id.pullUps, R.id.pushUps, R.id.rearDeltFlies,
                R.id.romanianDeadlifts, R.id.seatedDumbbellCurl, R.id.sitUps, R.id.shoulderPress, R.id.standingCurl,
    
    
        };
    
    
        return view;
    }
    
    public void Imagebuttonclicked(View view) {
    
    
        for (int i=0;i&lt; newArray.length;i++){
    
    
            if(view.getId() == newArray[i]) {
               int value = i+1;
               Log.i(&quot;FIRST&quot;, String.valueOf(value));
               Intent intent = new Intent(getActivity(),tutorialActivity.class);
               getActivity().startActivity(intent);
    
    
            }
        }
    
    }

}

Here is the stacktrace for the error that occurs when I press on the small arrow buttons:

> E FATAL EXCEPTION: main
> Process: com.example.neafitnessapp, PID: 23372
> java.lang.IllegalStateException: Could not find method
> Imagebuttonclicked(View) in a parent or ancestor Context for
> android:onClick attribute defined on view class
> android.widget.LinearLayout with id 'barbellRow'
> at
> android.view.View$DeclaredOnClickListener.resolveMethod(View.java:6359)
> at android.view.View$DeclaredOnClickListener.onClick(View.java:6316)
> at android.view.View.performClick(View.java:7506)
> at android.view.View.performClickInternal(View.java:7483)
> at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
> at android.view.View$PerformClick.run(View.java:29334)
> at android.os.Handler.handleCallback(Handler.java:942)
> at android.os.Handler.dispatchMessage(Handler.java:99)
> at android.os.Looper.loopOnce(Looper.java:201)
> at android.os.Looper.loop(Looper.java:288)
> at android.app.ActivityThread.main(ActivityThread.java:7872)
> at java.lang.reflect.Method.invoke(Native Method)
> at
> com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)

答案1

得分: 1

你的问题:

> 我已经尝试以许多方式更改意图语句,但每次程序仍然崩溃,而且我没有收到有关错误的任何详细信息。

崩溃告诉你确切的问题。调试问题的方法如下:

首先,查看实际引发的异常并阅读信息:

> java.lang.IllegalStateException: 在 android.widget.LinearLayout 类的 id 为 'barbellRow' 的视图上定义的 android:onClick 属性的父级或祖先上找不到方法 Imagebuttonclicked(View)。

你没有发布你的布局,但从这个非常详细的错误中,我们知道你在具有 id 'barbellRow' 的 LinearLayout 上设置了 android:onClick 属性为 Imagebuttonclicked(View) 方法。

我们还知道问题是该方法在“父级或祖先上找不到”。从文档中,对于 onClick,我们知道(重点是我的):

> 例如,如果您指定 android:onClick="sayHello",您必须在**您的上下文中(通常是您的 Activity)**声明一个名为 sayHello 的公共 void sayHello(View v) 方法。

从你的代码中,你的点击处理程序在你的 Fragment 中定义,而 Fragment 不是 Context,所以它失败了。

因此解决方案有两种选项之一:

1 - (首选)- 不要使用花哨的 onClick 属性,并在你的 Fragment 中显式地在 LinearLayout 上设置点击监听器。这将更明显,并将点击处理保持在你的 Fragment 中,而不是由 Activity 处理。

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    binding = FragmentExercisesBinding.inflate(getLayoutInflater(), container, false);
    View view = binding.getRoot();
    // 你现有的代码

    // 显式设置点击监听器
    binding.barbellRow.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Imagebuttonclicked(v);
        }
    });

    return view;
}

2 - 如果你想使用 onClick 属性,请将函数移动到包含 FragmentActivity 中,以满足该属性所需的条件。

英文:

Your Problem

> I have tried changing the intent statement in many ways but each time the program still crashes, and I'm not being given any details on the error.

The crash is telling you the exact problem. This is how to debug your issue:

First, look at the actual exception that was raised and read the information:

> java.lang.IllegalStateException: Could not find method Imagebuttonclicked(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.LinearLayout with id 'barbellRow'

You didn't post your layout but from this very detailed error we know you have a LinearLayout with id barbellRow on which you set the android:onClick attribute to the Imagebuttonclicked(View) method.

We also know that problem is that that method was not found "in a parent or ancestor Context". From the documentation, for onClick we know that (emphasis mine):

>For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity).

From your code, your click handler is defined in your Fragment and Fragment is not a Context, so it fails.

So the solution is one of two options:

1 - (Preferred) - Don't use the gimmicky onClick attribute and set the click listener on the LinearLayout explicitly in your Fragment. This will be more obvious and keeps your click handling local to your Fragment instead of having it being handle by the Activity.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    binding = FragmentExercisesBinding.inflate(getLayoutInflater(), container, false);
    View view = binding.getRoot();
    // Your existing code

    // Set onclicklistener explicitly
    binding.barbellRow.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Imagebuttonclicked(v);
        }
    });

    return view;
}

2 - If you want to use the onClick attribute, move the function to the Activity in which the Fragment lives to satisfy the conditions required by that attribute.

huangapple
  • 本文由 发表于 2023年4月17日 16:12:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032997.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定