从MainActivity Android Studio“刷新”片段布局
问题描述:
当我试图找出我的问题时,已经有一段时间了。从MainActivity Android Studio“刷新”片段布局
我想要“刷新”我的片段布局小部件,例如textviews,imageviews,cardviews和其他所有。
我试图做到这一点,如:
((ImageView) findViewById(R.id.BCFrame)).setImageResource(R.drawable.frame_1_6);
(Becouse这些对于 例如CardViews在其他布局。)但是,它总是显示,nullObjectPointer错误
我已经想通了,我可以刷新它们,当我点击该片段中的某处时,使用“onClick”功能
public void RefreshUpgrade(View view){
((TextView) findViewById(R.id.PlayerUpgradeTView)).setText("Player level: " +Main.PlayerLevel[0]);
((TextView) findViewById(R.id.BoxUpgradeTView)).setText("Box level: " + Main.BoxesLevel[0]);
((TextView) findViewById(R.id.GarageUpgradeTView)).setText("Garage level: " + Main.GarageLevel[0]);
((TextView) findViewById(R.id.GarageSlotsTView)).setText("Garage slots: " + Main.GarageSlots[0]);
((TextView) findViewById(R.id.short_description222)).setText("Money: " + Main.Money[0] + "/600");
((TextView) findViewById(R.id.short_description22)).setText("Boxes Opened: " + Main.BoxesOpened[0] + "/30");
if(Main.Money[0] >= 600){
((TextView) findViewById(R.id.short_description222)).setTextColor(0xff00ff00);
}
}
但我需要2件事,那是无法弄清楚的。
1.I需要这些对象“刷新”自动,如果参数是真(如果MainActivity语句)
2.我需要这些对象“刷新”自动,经过一段时间后都去了(像GameLoop )。
在简单的Java我得到了这一切工作,但在那里我只有JPanels,没有像片段。
答
请勿在您的活动中搜索属于片段的Views
。在你的Fragment
类中,它们存储在诸如例如
class Fragment
private TextView playerUpgradeTextView;
public void refreshViews(){
// your refreshUpgrade() method
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.yourFragmentLayout, container, false);
playerUpgradeTextView = (TextView) v.findViewById(R.id.PlayerUpgradeTView)
return v;
}
由于您Activity
握着你的Fragment
可以调用refreshViews
方法,如果需要传递方法参数。
第二个问题更多的是一个经典的周期性事件,它也称为refreshViews
方法。
答
你可以尝试“重建”你的片段并强制它调用onCreateView
。
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();
为您自动刷新:
创建一个处理程序
Handler handler = new Handler();
创建Runnable对象句柄的
public final Runnable runnable = new Runnable() {
@Override
public void run() {
// your code to refresh
}
};
调用方法r对象
handler.postDelayed(runnable, yourdelay);
@trakasi这是一个不同的问题,但你的'ClickerFragment'扩展'Fragment'?否则,看看打开一个新的问题。 –
谢谢,看起来像这是工作,但得到了问题.. java.lang.NullPointerException:尝试调用虚拟方法'void com.crelix.crelix.ClickerFragment。refreshViews()'空对象引用 – trakasi
是的,它是扩展的,并且在ClickerFragment方法中,refreshViews显示为“used”(Android Studio中的黄色) – trakasi