我有两个布局table.xml(port)和table.xml(land),其中有一个是横向的,另一个是protrait。
我已将此布局包含在另一个名为fragment_test.xml的布局中,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<include layout="@layout/table"/>
</RelativeLayout>
这是我上面布局fragment_test的片段代码:
public class Fragment_test extends Fragment implements View.OnTouchListener{
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mytable= (LinearLayout) getActivity().findViewById(R.id.mytableid);
typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/font.ttf");
for (int i = 0; i < table1.getChildCount(); i++) {
LinearLayout mychild = (LinearLayout) mytable.getChildAt(i);
for (int j = 0; j < mychild.getChildCount(); j++) {
Button b = (Button) child.getChildAt(j);
b.setTypeface(typeface);
b.setOnTouchListener(this);
}
}
}
}
//this is called when a button is touched
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return true;
}
}
所以基本上我在表格布局中有几个按钮,我正在为每个按钮循环到setontouchlistener。
所以我的问题是当我从protrait切换到横向或相反时按钮的touchlistener不再起作用,甚至在更改布局时字体不再起作用。
&GT;修改:这是活动代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
FragmentManager manager = getFragmentManager();
manager.beginTransaction().add(R.id.container, new Fragment_test(), "mytag").commit();
}
答案 0 :(得分:1)
尝试在setRetainInstance(true)
super.onActivityCreated(savedInstanceState);
here is the documentation of setRetainInstance(boolean)
活动:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
FragmentManager manager = getSupportFragmentManager();
Fragment myFragment = manager.findFragmentByTag("myFragment");
if (myFragment == null) {
myFragment = new ParentFragment();
}
manager.beginTransaction().add(R.id.fragmentHolder, myFragment, "myFragment").commit();
}
}
片段:
public class ParentFragment extends Fragment{
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}
答案 1 :(得分:0)
我只是给你提供信息。
您可以通过这种方式查看设备Orientataion
并设置布局。
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
setContentView(R.layout.table_horizontal);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}else if (newConfig.orientation==Configuration.ORIENTATION_PORTRAIT){
setContentView(R.layout.table_vertical);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
}