我想创建一个ViewPager其宽度包裹的它的内容,并集中在水平它的父。第一个代码片段使用LinearLayout来创建这种效果,如第一个屏幕截图所示。第二个代码片段是我尝试使用ViewPager而不是LinearLayout完成的,但结果不是所需的行为,如第二个屏幕截图所示。Android:ViewPager不尊重WRAP_CONTENT?
任何建议,我如何创建第一个效果,但使用ViewPager?
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
textView = new TextView(this);
textView.setLayoutParams(new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setText("abcabcabcabcabc");
textView.setBackgroundColor(Color.YELLOW);
LinearLayout llayout = new LinearLayout(this);
llayout.setBackgroundColor(Color.BLUE);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
llayout.setLayoutParams(layoutParams);
llayout.addView(textView);
layout = new RelativeLayout(this);
layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
layout.setBackgroundColor(Color.GREEN);
layout.addView(llayout);
setContentView(layout);
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
textView = new TextView(this);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewPager.LayoutParams.WRAP_CONTENT, ViewPager.LayoutParams.WRAP_CONTENT));
textView.setText("abcabcabcabcabc");
textView.setBackgroundColor(Color.YELLOW);
ViewPager pager = new ViewPager(this);
pager.setBackgroundColor(Color.BLUE);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
pager.setLayoutParams(layoutParams);
pager.setAdapter(new ViewPagerAdapter());
layout = new RelativeLayout(this);
layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
layout.setBackgroundColor(Color.GREEN);
layout.addView(pager);
setContentView(layout);
}
class ViewPagerAdapter extends PagerAdapter
{
@Override
public int getCount()
{
return 1;
}
public Object instantiateItem(ViewGroup collection, int position)
{
collection.addView(textView, 0);
return textView;
}
@Override
public void destroyItem(ViewGroup collection, int position, Object view)
{
collection.removeView((View) view);
}
@Override
public boolean isViewFromObject(View view, Object object)
{
return (view==object);
}
@Override
public void finishUpdate(ViewGroup arg0) {}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
@Override
public Parcelable saveState()
{
return null;
}
@Override
public void startUpdate(ViewGroup arg0) {}
}
你为什么不只是使用XML布局文件和的setContentView给他们? –
适合我不适合。虽然,如果它不能在代码中工作,我怀疑它会在xml中工作。 (并不重要,因为我需要用Java编写布局)。 – ab11
@ ab11那么屏幕的绿色部分是什么。如果它是内容的另一个“页面”,那么当你在最右或最左边时会发生什么。否则,你不能坚持水平线性布局来获得你想要的效果吗? –