首先我创建导航抽屉活动的应用程序并从片段到新活动,现在我想在导航到导航抽屉的主要活动的新活动上设置主页按钮。我试着使用这段代码:
class bitter_gourd_node_c(models.Model):
node_id=models.ForeignKey(Nodes)
record_no= models.AutoField(blank=True,primary_key=True)
data_date=models.DateTimeField()
humidity=models.DecimalField(max_digits=14,decimal_places=10)
amb_temp=models.DecimalField(max_digits=14,decimal_places=10)
deep_under_temp=models.DecimalField(max_digits=14,decimal_places=10)
shallow_under_temp=models.DecimalField(max_digits=14,decimal_places=10)
deep_soil_moisture=models.DecimalField(max_digits=14,decimal_places=10)
shallow_soil_moisture=models.DecimalField(max_digits=14,decimal_places=10)
ldr=models.DecimalField(max_digits=14,decimal_places=10)
但是显示错误,因为很遗憾您的应用已停止
答案 0 :(得分:0)
我们需要更多详细信息才能为您提供帮助。 我首先注意到的是这一行
Intent intent = new Intent(add_activity.this,MainFragment.class);
startActivity(intent);
finish();
问题在于你不能用Intent启动片段。
如果您想从 MainActivity 启动 TravelActivity ,请执行以下操作:
Intent intent = new Intent (this /*indicating your current activity*/, TravelActivity.class /*indicating Activity you want to start*/)
startActivity(intent); //start TravelActivity
finish() //finish current activity - if you press back you will exit the app (if MainActivity was launcher activity)
如果您有启动Travel活动时应加载的片段,则以下是一个简单的帮助方法,可以为您执行片段事务
public void replaceFragment(int rootViewId, Fragment fragment, boolean addToBackStack) {
try {
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragment == null)
return;
if (checkIfFragmentIsCurrent(fragment, rootViewId))
return;
String backStateName = fragment.getClass().getSimpleName();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(rootViewId, fragment);
if (addToBackStack) {
transaction.addToBackStack(fragment.getClass().getSimpleName());
}
transaction.commit();
}
} catch (Exception e) {
Log.e("ReplaceFragment", "Exception: " + e.getMessage());
}
}
protected boolean checkIfFragmentIsCurrent(Fragment fragment, int placeHolderRes) {
Fragment currentFragment = getSupportFragmentManager().findFragmentById(placeHolderRes);
if (fragment != null && currentFragment != null) {
if (fragment.getClass().equals(currentFragment.getClass())) {
return true;
}
}
return false;
}
为了使用它,只需调用replacFragment(将容纳您的片段的容器的ID,Fragment实例,如果您想将片段添加到backStack,则为true)
了解此link
的片段交易