我有一个android片段,它有一个listview。对于该列表视图,我实现了一个内部的OnItemClickListener类。 单击时,我将选择保存在名为SelectedIndex的全局变量中。
如果我再次点击该列表,我可以正确看到上一个选择,因此它正确地保存了全局变量的状态。
问题是当我尝试从另一个内部类访问同一个全局变量时,例如,一个用于监听按钮点击的类。始终显示我用于初始化varialbe(-1)的值。
片段的代码:
/**
* A placeholder fragment containing the view for the recentCalls list
*/
public class RecentCallsFragment extends Fragment {
private Cursor cursorAllRows;
private RecentCallsTable rcTable;
private ListView list;
private RecentCallsAdapter adapter;
Button btnDelete, btnCreditRequest, btnCreditBlock, btnSendTo;
int selectedIndex; //this is the global variable that I am using.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rcTable = new RecentCallsTable(getActivity());
cursorAllRows = rcTable.getRecentCallsCursor();
adapter = new RecentCallsAdapter(getActivity(), cursorAllRows);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
list = (ListView) view.findViewById(R.id.listViewMain);
btnDelete = (Button) getActivity().findViewById(R.id.buttonDelete);
btnCreditRequest = (Button) getActivity().findViewById(R.id.buttonCr);
btnCreditBlock = (Button) getActivity().findViewById(R.id.buttonCRD);
list.setAdapter(adapter);
list.setOnItemClickListener(new ItemClickHandler()); //Add the inner ItemClickLister
btnSendTo = (Button) getActivity().findViewById(R.id.buttonSendTo);
btnSendTo.setOnClickListener(new DebugOnClick());//here I add the inner clicklister
return view;
}
/**
* Class that handles the one click action on the list
*/
public class ItemClickHandler implements AdapterView.OnItemClickListener{
//when there's one fast click, keep the selection on the item or remove it if already has it
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
int prevSelection = adapter.getSelectedIndex();
Toast.makeText(getActivity(), Integer.toString(selectedIndex), Toast.LENGTH_SHORT).show();
int newSelection = position;
if(prevSelection == position){
newSelection = -1;
}
selectedIndex = newSelection; //here I change the value of the global variable
adapter.setSelectedIndex(newSelection);
adapter.notifyDataSetChanged();
}
}
public class DebugOnClick implements View.OnClickListener{
public DebugOnClick(){
}
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), Integer.toString(selectedIndex), Toast.LENGTH_SHORT).show(); //here I show the value of the global variable and is always -1
}
}
}
可能是哪个问题?
答案 0 :(得分:0)
有一种可能性进入我的脑海。当您实例化内部类时,它会隐式绑定托管类的实例(就好像它是托管类的引用)。因此,我假设您使用的内部类每个都与托管类的不同实例链接,因此使用不同的selectedIndex。你的全局变量不是真正的全局变量,它是一个实例变量。
答案 1 :(得分:0)
我刚发现了这个问题。这些按钮位于主要活动中,所以我只是将全局变量移动到主Activity并开始从这样的片段中操作它:
MainActivity ma = (MainActivity) getActivity();
ma.rcSelected = newSelection;