【问题标题】:Button intent in TabFragment activity?TabFragment 活动中的按钮意图?
【发布时间】:2015-09-16 17:56:55
【问题描述】:
public class Home extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.home,null);


    }}

这是片段标签 1 的完整代码。 我有一个带有两个 TabFragments 的程序,我想在片段选项卡 1 和 2 中声明一个图像按钮和按钮意图,但我做不到,并且 findviewbyid 不起作用..

我可以做些什么来声明按钮的意图?

【问题讨论】:

  • 只需将所需的视图添加到您的 XML 资源文件中,该文件似乎是 res/layout/home.xml
  • 我在我的 xml 文件中有一个 textview 和 button 和 image 按钮、card view,但我无法在 home java 文件中定义它们以对另一个页面产生意图?
  • 我想我不明白你的问题是什么。你有你的 XML 视图,它们在 onCreateView 方法中被夸大了。您是否正在寻找一种方法来处理您的按钮点击?
  • Button myButton = (Button) findViewById(R.id.imageButton);如果我写这个命令(findViewByid)不起作用并且它的颜色是红色的,
  • 是的,我想要方法来处理我的按钮点击

标签: android android-fragments android-intent


【解决方案1】:

使用View.OnClickListener 接口来处理按钮点击(和一般的查看点击)。您所要做的就是覆盖其onClick 方法并通过调用setOnClickListener() 将其分配给视图。

您还可以找到详尽的教程here

UPD:您的方法应如下所示:

public View onCreateView(.....) {

    // assign inflated view to a variable
    View v = inflater.inflate(R.layout_services, null);

    // set your listener
    v.findViewById(R.id.imageButton).setOnClickListener(.....);

    // return the view in the end
    return v;
}

问题是您会立即返回膨胀的视图,而下面的代码根本无法运行,这就是出现该错误的原因。

UPD2: 现在的问题是startActivity 方法接收Context 作为第一个参数,所以你应该通过调用getActivity() 来传递你的活动(而不是传递Services.this )。你可以阅读更多here

UPD3:您似乎不了解您的代码的作用。您的 findViewById 调用没有用,因为它没有被分配给变量,而您的 setOnClickListener 被应用于整个片段视图。这部分应该是这样的:

ImageButton button = (ImageButton) v.findViewById(R.id.imageButton);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Activity activity = getActivity();
        Intent intent = new Intent(activity, Admin.class);
        activity.startActivity(intent);
    }
});

我建议在尝试实际编写应用程序之前了解所有这些方法的工作原理(至少看看参考资料,首先是:herehere)。祝你好运。

【讨论】:

猜你喜欢
  • 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
相关资源
最近更新 更多