我有一個WearableActivity作爲我的主要活動,我想爲不同的佈局使用片段。麻煩的是,當我嘗試在片段中使用getActivity()獲取對主活動的引用時,Android Studio說我無法從FragmentActivity投射到MainWearActivity(它擴展了WearableActivity)。如何在由Android中的WearableActivity啓動的片段中使用getActivity?
我MainWearActivity類:
public class MainWearActivity extends WearableActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
private WatchViewStub mContainerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wear);
mContainerView = (WatchViewStub) findViewById(R.id.mainContainer);
mContainerView.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override
public void onLayoutInflated(WatchViewStub watchViewStub) {
}
});
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onEnterAmbient(Bundle ambientDetails) {
super.onEnterAmbient(ambientDetails);
}
@Override
public void onUpdateAmbient() {
super.onUpdateAmbient();
}
@Override
public void onExitAmbient() {
super.onExitAmbient();
}
}
我的片段類:
public class NavigationFragment extends Fragment {
View view;
MainWearActivity mMainWearActivity;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.navigation_fragment, container, false);
mMainWearActivity = (MainWearActivity) getActivity(); // ERROR HERE
return view;
}
}
當我嘗試投getActivity()的結果,我的主要活動也不會允許我。任何人都可以幫我解決這個問題嗎?我需要參考我的主要活動,以便將其用作上下文。由於
編輯
字符串的回答下面的問題解決了。然而,我想補充一點,就是如果你使用片段尋呼機適配器,你必須將「compile」com.android.support:support-v13:23.1.1'「添加到你的build.gradle ,並使用支持v13 pager的適配器,它允許你從GetItem()返回一個android.app.Fragment。
包含您的NavigationFragment的佈局是什麼樣的?您是否將NavigationFragment直接添加到MainWearActivity或其他活動? – dazza5000