我想創建一個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那麼屏幕的綠色部分是什麼。如果它是內容的另一個「頁面」,那麼當你在最右或最左邊時會發生什麼。否則,你不能堅持水平線性佈局來獲得你想要的效果嗎? –