我是初学者使用Android工作室我目前观看了一些关于设置基本滑动视图的教程,该视图最多可生成3个将我的代码中已知的原始页面复制为page_fragment_layout.xml。我想更进一步,能够链接包含一系列内容的不同页面。在这种情况下,我希望能够通过滑动将我的Activity_main.xml和page_fragment_layout.xml链接在一起。到目前为止,我已添加了我的代码,我非常感谢任何输入。
MainActivity.java
package socialdeveloper.swipecard;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.view_pager);
SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager());
viewPager.setAdapter(swipeAdapter);
}
}
PageFragment.java
package socialdeveloper.swipecard;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class PageFragment extends android.support.v4.app.Fragment {
TextView textView;
public PageFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.page_fragment_layout,container,false);
textView = (TextView)view.findViewById(R.id.TestText);
Bundle bundle = getArguments();
String message = Integer.toString(bundle.getInt("count"));
textView.setText("This is the "+message+ "Swipe View Page...");
return view;
}
}
SwipeAdapter.java
package socialdeveloper.swipecard;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by Hadleigh on 07/12/2015.
*/
public class SwipeAdapter extends FragmentStatePagerAdapter {
public SwipeAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = new PageFragment();
Bundle bundle = new Bundle();
int i = 0;
bundle.putInt("count",i+1);
fragment.setArguments(bundle);
return fragment;
}
@Override
public int getCount() {
return 3;
}
}
答案 0 :(得分:0)
使用此
` public Fragment getItem(int position) {
Fragment fragment = null;//Creates a fragment variable to hold the fragment class i create and make it a null so i can catch the error
if (position == 0) {
fragment = new PUT_THE_TITLE_OF_YOUR_ACTIVITY_YOU_WANT_TO_USE();//Calls the fragment.
}
if (position == 1) {
fragment = new CALL_A_DIFFERENT_FRAGMENT_OR_ACTIVITY();//Calls the fragment;
}
if (position == 2) {
fragment = new CALL_A_DIFFERENT_FRAGMENT_OR_ACTIVITY();//Calls the fragment.
}
return fragment;
}`
在 getItem()方法中调用其他片段或活动。