我想調用片段按鈕單擊這是一個片段。我試過這段代碼,但它不工作。當我點擊按鈕時顯示下一個片段而不是它的設計。我只看到一個空白頁。如何使用viewpager從tablayout中的另一個片段調用片段
這是我的主要的xml: -
<LinearLayout
android:id="@+id/main_layout"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- our toolbar -->
<!-- our tablayout to display tabs -->
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabGravity="fill"
android:background="#fa4022"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>
我在這TabLayout的儀表盤選項卡。在這個儀表板選項卡中,我有一個按鈕,其id是userprofile。點擊此按鈕,我想要去user_profile.xml
public class Dashboard extends Fragment implements View.OnClickListener {
Button userprofile;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dashboard, container, false);
userprofile=(Button)rootView.findViewById(R.id.userprofile);
userprofile.setOnClickListener(this);
return rootView;
}
@Override
public void onClick(View view) {
Fragment fragment = null;
switch (view.getId()) {
case R.id.userprofile:
fragment = new User_Profile();
replaceFragment(fragment);
break;
}
}
private void replaceFragment(Fragment fragment) {
User_Profile user_profile = new User_Profile();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.pager, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
User_Profile類代碼後: -
public class User_Profile extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rooView=inflater.inflate(R.layout.user_profile, container, false);
return rooView;
}
}
user_profile.xml是: -
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Profile"
android:textSize="30dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
我的xml只有一個簡單的textview。檢查我的編輯 –