导致活动不工作的片段中的按钮(更新)
Posted
技术标签:
【中文标题】导致活动不工作的片段中的按钮(更新)【英文标题】:Buttons in a fragment leading to an activity not working (updated) 【发布时间】:2020-09-04 19:43:28 【问题描述】:我有一个带有 2 个按钮的片段,用于引导新活动。我已经获得了一些先前的反馈并创建了新代码。但是仍然没有任何效果,甚至打印语句也没有被触发
package com.example.workoutapp;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class CreateFragment extends Fragment
public Button button;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState)
View v = inflater.inflate(R.layout.fragment_create, container, false);
Button Workoutbutton=(Button)v.findViewById(R.id.Workoutbutton);
Button Timersbutton=(Button)v.findViewById(R.id.Timerbutton);
Workoutbutton.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
System.out.println("Workouts Clicked");
Intent intent=new Intent(getActivity(),WorkoutsCreater.class);
startActivity(intent);
);
Timersbutton.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
System.out.println("Timers Pressed");
Intent intent=new Intent(getActivity(),TimersCreater.class);
startActivity(intent);
);
return inflater.inflate(R.layout.fragment_create, container, false);
【问题讨论】:
【参考方案1】:package com.example.workoutapp;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class CreateFragment extends Fragment implements View.OnClickListener
public Button workoutButton;
public Button timersButton;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_create, container, false);
workoutButton=view.findViewById(R.id.Workoutbutton);
workoutButton.setOnClickListener(this);
timersButton=view.findViewById(R.id.Timerbutton);
timersButton.setOnClickListener(this);
return view;
@Override
public void onClick(View v)
switch (v.getId())
case R.id.Workoutbutton:
System.out.println("Workout Button Pressed");
break;
case R.id.Timerbutton:
System.out.println("Timers Button Pressed");
break;
【讨论】:
以上是关于导致活动不工作的片段中的按钮(更新)的主要内容,如果未能解决你的问题,请参考以下文章