簡體   English   中英

我如何從片段中訪問活動中的按鈕ID

[英]how can i access the button id in activity from fragment

如何訪問活動中的按鈕ID。

活動

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_meter);
    if (Build.VERSION.SDK_INT >= 23) {
        checkLocationPermission();
    }



 FragmentManager fragmentManager =  getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment map = new Map();
    fragmentTransaction.add(R.id.fragment_container, map);
    fragmentTransaction.commit();

 ...
}

分段

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




  if (view == null) {
        view = inflater.inflate(R.layout.fragment_map, container, false);

        Button button = (Button)getActivity().findViewById(R.id.btnStop);

    }

如何在我的代碼片段中實現btnStop的setOnClickListener方法?

將此添加到片段:

final View.OnClickListener btnClick = new View.OnClickListener() {
                           public void onClick(View v){
                               //button clicked 
                           }
                     }

將此添加到活動onCreate

Button button = (Button)getActivity().findViewById(R.id.btnStop);
button.setOnClickListener(map.btnClick );

其他方式:

將此添加到片段:

Button btnStop;

將此添加到Activity的onCreate中:

map.btnStop = (Button)getActivity().findViewById(R.id.btnStop);

然后,在Activity的onCreate之后調用的片段的任何事件監聽器(例如onActivityCreatedonStart )中,您都可以訪問btnStop並且可以btnStop設置onClick監聽器。

You can create a method in the activity, probably like

public void yourMethod() {

button.performClick();// you can access all the components present in your activity

}

Now create an instance of the activity in the fragment and access this method.

YourActivity activityInstance = (YourActivity) getActivity();

And then you can access the method using the isntance of the activity like

activityInstance.yourMethod();

每當您要執行單擊功能時,只需調用功能鍵即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM