java [Fragment片段] #Android #UI
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java [Fragment片段] #Android #UI相关的知识,希望对你有一定的参考价值。
//在Fragment获取控件ID
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.activity_main2, container, false);
Button button = v.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
new AlertDialog.Builder(v.getContext())
.setIcon(R.drawable.ic_launcher_background)
.setTitle("提示")
.setMessage("button")
.setNeutralButton("确定", null)
.create()
.show();
}
});
return v;
}
public class MainActivity extends AppCompatActivity {
//声明两个管理器
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
//new个Fragment类
private Query fragment1 = new Query();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取两个管理器
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
//把new的Fragment加入到容器里
fragmentTransaction.add(R.id.frameLayout, fragment1);
//fragmentTransaction.add(R.id.frameLayout, fragment2);
//隐藏某个Fragment
//fragmentTransaction.hide(fragment2);
fragmentTransaction.commit();
}
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取Fragment
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//显示某个Fragment
fragmentTransaction.show(fragment1);
//隐藏某个Fragment
fragmentTransaction.hide(fragment2);
fragmentTransaction.commit();
//有bug,replace后所有的界面都没有了
////重新加载某个界面.replace
// fragmentTransaction.replace(R.id.frameLayout, fragment_query);
// fragmentTransaction.hide(fragment_add);
// fragmentTransaction.show(fragment_query);
// fragmentTransaction.commit();
}
});
}
以上是关于java [Fragment片段] #Android #UI的主要内容,如果未能解决你的问题,请参考以下文章
每当我尝试从 Fragment java 文件中更改片段的某些属性时,应用程序就会崩溃
Java Android - 将数据从活动发送到片段
我的片段无法转换为 android.support.v4.app.Fragment
我无法在 Home Fragment 中获取 Support Fragment?
在 webview 片段中实现后退按钮
带有片段的 Kotlin