我有一个带有列表视图和按钮的活动,当点击按钮时我会添加一个片段。我的问题是,当我滚动片段然后关闭片段时,活动中的列表视图也会滚动,当我单击按钮将片段带回应用程序崩溃时。有什么帮助吗?
主要活动代码
public class MainActivity extends Activity implements OnClickListener {
ListView listView ;
Button B;
FragmentTransaction fragmentTransaction;
FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
listView = (ListView) findViewById(R.id.list);
// Defined Array values to show in ListView
String[] values = new String[] { "1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
B=(Button)findViewById(R.id.button1);
B.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button1:
Second s = new Second();
fragmentTransaction.add(android.R.id.content, s);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack("Cam");
fragmentTransaction.commit();
break;
}
}
}
答案 0 :(得分:1)
将此添加到以下内容:
switch(v.getId())
{
case R.id.button1:
Second s = new Second();
//add this
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, s);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
break;
}
答案 1 :(得分:1)
试试这个::
从fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
方法
onCreate(...){...}
并将此代码放在该案例上,即
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button1:
Second s = new Second();
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(android.R.id.content, s);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack("Cam");
fragmentTransaction.commit();
break;
}
}