我有一个框架布局,想要根据数组的当前状态更改背景图像/颜色。我可以根据数组更改文本,因此了解如何执行此操作但无法找到引用布局的方法。
我在创建之后初始化了帧布局(li)但是当我尝试在后面的方法中更改颜色时,我得到错误“非静态字段'li'不能从静态上下文中引用”。
任何帮助表示赞赏
public class GridViewFragmentActivity extends FragmentActivity
{
FrameLayout li;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FrameLayout li =(FrameLayout) findViewById(R.id.framelayout);
final DotsPageIndicator mPageIndicator;
final GridViewPager mViewPager;
final String[][] data =
{
{ "Row 0, Col 0", "Row 0, Col 1", "Row 0, Col 2", "Row 0, Col 3" },
{ "Row 1, Col 0", "Row 1, Col 1", "Row 1, Col 2" },
{ "Row 2, Col 0", "Row 2, Col 1", "Row 2, Col 2" }
};
// Get UI references
mPageIndicator = (DotsPageIndicator) findViewById(R.id.page_indicator);
mViewPager = (GridViewPager) findViewById(R.id.pager);
// Assigns an adapter to provide the content for this pager
mViewPager.setAdapter(new GridPagerAdapter(getFragmentManager(), data));
mPageIndicator.setPager(mViewPager);
}
private static final class GridPagerAdapter extends FragmentGridPagerAdapter {
String[][] mData;
private GridPagerAdapter(FragmentManager fm, String[][] data)
{
super(fm);
mData = data;
}
@Override
public Fragment getFragment(int row, int column)
{
String text = "CARD FRAGMENT";
if (row == 2 && column == 1)
{
text = "SIT UP";
li.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
else
{
text = "PRESS UP";
li.setBackgroundColor(Color.parseColor("#FF0000"));
}
return (CardFragment.create(text, mData[row][column]));
}
@Override
public int getRowCount()
{
return mData.length;
}
@Override
public int getColumnCount(int row)
{
return mData[row].length;
}
}
}
答案 0 :(得分:1)
通过GridPagerAdapter构造函数传递布局并保存在变量中。
private static final class GridPagerAdapter extends FragmentGridPagerAdapter {
private final FrameLayout li;
String[][] mData;
private GridPagerAdapter(FragmentManager fm, String[][] data, FrameLayout li)
{
super(fm);
mData = data;
this.li = li;
}
//... stuff
}
然后相应地修改你的onCreate方法
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FrameLayout li =(FrameLayout) findViewById(R.id.framelayout);
final DotsPageIndicator mPageIndicator;
final GridViewPager mViewPager;
final String[][] data =
{
{ "Row 0, Col 0", "Row 0, Col 1", "Row 0, Col 2", "Row 0, Col 3" },
{ "Row 1, Col 0", "Row 1, Col 1", "Row 1, Col 2" },
{ "Row 2, Col 0", "Row 2, Col 1", "Row 2, Col 2" }
};
// Get UI references
mPageIndicator = (DotsPageIndicator) findViewById(R.id.page_indicator);
mViewPager = (GridViewPager) findViewById(R.id.pager);
// Assigns an adapter to provide the content for this pager
mViewPager.setAdapter(new GridPagerAdapter(getFragmentManager(), data, li));
mPageIndicator.setPager(mViewPager);
}