我是安卓新手。因此,我一直在研究 fragment 以了解它们的工作原理。
首先,我创建了一个 calciKeyboard
类,它扩展了 Fragment
代码:
public class calciKeyboard extends Fragment {
@Nullable
Button b;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
GridLayout gridLayout=(GridLayout) inflater.inflate(R.layout.calci_keyboard,container,false);
for(int i=0;i<gridLayout.getChildCount();i++){
b=(Button)gridLayout.getChildAt(i);
if (b != null) {
b.setBackground(getResources().getDrawable(R.drawable.button_dark_gradient));
}
}
return gridLayout;
}
}
calciKeyboard.xml
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="4"
android:columnCount="4"
>
Buttons inside....
</GridLayout>
advance_mix
public class advance_mix extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.advance_length);
}
}
advance_length
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.tilak.myfirstapplication.calciKeyboard"
android:id="@+id/calciKeyboard" />
</GridLayout>
go_advance.java
findViewById(R.id.redirectLength).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(go_advance.this,advance_mix.class);
startActivity(i);
}
}
);
go_advance
类包含启动 advance_mix
Activity 的 Intent ,它进一步布置了 advance_length
布局文件。
问题是当 redirect_length
按钮被点击时,它显示了一个白屏。
为什么会这样?
最佳答案
您应该返回
View 。
View getRootView = inflater.inflate(R.layout.calci_keyboard,container,false);
GridLayout gridLayout=(GridLayout)getRootView.findViewById(R.id._gridLAYOUT);
for(int i=0;i<gridLayout.getChildCount();i++){
b=(Button)gridLayout.getChildAt(i);
if (b != null) {
b.setBackground(getResources().getDrawable(R.drawable.button_dark_gradient));
}
return getRootView ;
XML
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/_gridLAYOUT">
<fragment android:layout_width="match_parent" //Change this to match_parent
android:layout_height="match_parent" //Change this to match_parent
android:name="com.example.tilak.myfirstapplication.calciKeyboard"
android:id="@+id/calciKeyboard" />
</GridLayout>
关于android - 调用 fragment 时出现白屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47526854/