如何在TabLayout中添加按钮单击?

时间:2018-08-20 20:24:05

标签: android android-tablayout layout-inflater

如何在TabLayout中添加按钮单击?我到处都尝试过,但是无法实现R.idonclicklisener

我的xml:

<LinearLayout
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">


<Button
    android:id="@+id/start"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />

    <Button
        android:id="@+id/quiz2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />
</LinearLayout>

我的java类:

   public class ChatFragment extends Fragment {
   @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    setHasOptionsMenu(true);
    return inflater.inflate(R.layout.fragment_chat, container, false);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_calls, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_call) {
        Toast.makeText(getActivity(), "Clicked on " + item.getTitle(), Toast.LENGTH_SHORT)
                .show();
    }
    return true;
}
}

我将本教程用于布局:https://www.youtube.com/watch?v=Vxiy_h5hNII

github:https://github.com/codingdemos/Tablayout

2 个答案:

答案 0 :(得分:0)

您必须添加:private Button mButton2;延伸片段{

之后

然后您将onCreateView中的return更改为View视图。之后,在setHasOptionsMenu(true)之前添加mButton2 =(按钮)view.findViewById(R.id.button2)。之后,您应该可以找到自己的ID。

答案 1 :(得分:0)

public class StatusFragment extends Fragment {
Button button2;




@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


   View StatusFragmentView=inflater.inflate(R.layout.fragment_status, container, false);
   button2= StatusFragmentView.findViewById(R.id.quiz2);
   setHasOptionsMenu(true);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent=new Intent(getActivity(),Splash.class);
            startActivity(intent);
        }
    });


    return StatusFragmentView;
    }

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_calls, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_call) {
        Toast.makeText(getActivity(), "Clicked on " + item.getTitle(), Toast.LENGTH_SHORT)
                .show();
    }
    return true;
}

}